/* ============================================================
   Динамика веса — overview + detail
   ============================================================ */

/* Reusable weight line chart.
   data: [{x:'Янв', kg:29}]   markers:[{i, L, c}] vertical event lines
   W/H in svg units; y-domain fixed 23..33 */
function WeightChart({ data, markers, yMax=31, openIdx, lastHollow }){
  const W=320, H=190, padL=26, padR=14, padT=24, padB=26;
  const yMin=23;
  const x=i=> padL + (W-padL-padR)*(i/(data.length-1));
  const y=kg=> padT + (H-padT-padB)*(1-(kg-yMin)/(yMax-yMin));
  const pts=data.map((d,i)=>[x(i),y(d.kg)]);
  const gridVals=[]; for(let v=yMin;v<=yMax;v+=2) gridVals.push(v);
  const mColor={A:"#F06455",S:"#2A6FDB",V:"#20A83A"};
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{display:"block"}}>
      <text x="6" y={padT-8} fontSize="11" fill="#8B929C" fontWeight="600">кг</text>
      {gridVals.map(v=>(
        <g key={v}>
          <text x="6" y={y(v)+4} fontSize="11" fill="#A2A8B0" fontWeight="500">{v}</text>
        </g>
      ))}
      {/* event vertical dashed lines + letter badges */}
      {markers.map((m,k)=>(
        <g key={k}>
          <line x1={x(m.i)} y1={padT-2} x2={x(m.i)} y2={H-padB} stroke={mColor[m.L]} strokeWidth="1.2" strokeDasharray="3 3" opacity=".5"/>
          <circle cx={x(m.i)} cy={padT-6} r="9" fill="#fff" stroke={mColor[m.L]} strokeWidth="1.6"/>
          <text x={x(m.i)} y={padT-2.5} fontSize="11" fontWeight="700" fill={mColor[m.L]} textAnchor="middle">{m.L}</text>
        </g>
      ))}
      <polyline points={pts.map(p=>p.join(",")).join(" ")} fill="none" stroke="#20A83A" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
      {pts.map((p,i)=>{
        const hollow = lastHollow && i===pts.length-1;
        const open = openIdx===i;
        return <g key={i}>
          {open && <circle cx={p[0]} cy={p[1]} r="7" fill="#fff" stroke="#20A83A" strokeWidth="2.4"/>}
          <circle cx={p[0]} cy={p[1]} r={open?3.2:3.4} fill={hollow?"#fff":"#20A83A"} stroke="#20A83A" strokeWidth={hollow?2:0}/>
        </g>;
      })}
      {data.map((d,i)=> <text key={i} x={x(i)} y={H-8} fontSize="11" fill="#8B929C" fontWeight="500" textAnchor="middle">{d.x}</text>)}
    </svg>
  );
}

const data6=[{x:"Янв",kg:28.8},{x:"Фев",kg:28.4},{x:"Мар",kg:27.6},{x:"Апр",kg:26.2},{x:"Май",kg:26.9},{x:"Июн",kg:26.8}];
const markers6=[{i:3,L:"A"},{i:4,L:"S"},{i:5,L:"V"}];
const data12=[{x:"Июл",kg:31},{x:"Авг",kg:30.6},{x:"Сен",kg:30.2},{x:"Окт",kg:30.3},{x:"Ноя",kg:30},{x:"Дек",kg:29.8},{x:"Янв",kg:29.6},{x:"Фев",kg:29},{x:"Мар",kg:28.2},{x:"Апр",kg:27.4},{x:"Май",kg:28},{x:"Июн",kg:27.6}];
const markers12=[{i:9,L:"A"},{i:10,L:"S"},{i:11,L:"V"}];

function WHeader({ go }){
  return (
    <AppBar onBack={()=>go("home")} right={<button className="iconbtn"><Icon.gear/></button>}
      title={null}
    />
  );
}
function WTitle(){
  return (
    <div style={{padding:"0 22px",display:"flex",alignItems:"center",gap:14}}>
      <div style={{width:56,height:56,borderRadius:16,border:"2.5px solid var(--green)",background:"#fff",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--green)",flex:"none"}}><Icon.paw s={28}/></div>
      <div className="col">
        <div className="h1" style={{fontSize:28,margin:0,whiteSpace:"nowrap"}}>Динамика веса</div>
        <div className="sub" style={{fontSize:15,whiteSpace:"nowrap"}}>Лилу · Корги · 3 года</div>
      </div>
    </div>
  );
}

function Segmented({ value, onChange }){
  const opts=["1м","3м","6м","1г"];
  return (
    <div style={{display:"flex",background:"var(--card-gray)",borderRadius:16,padding:5,gap:4}}>
      {opts.map(o=>(
        <button key={o} onClick={()=>onChange(o)} style={{flex:1,height:42,borderRadius:12,fontSize:16,fontWeight:700,
          background:o===value?"#fff":"transparent",color:o===value?"var(--ink)":"var(--gray)",
          boxShadow:o===value?"var(--shadow-soft)":"none"}}>{o}</button>
      ))}
    </div>
  );
}

function LegendPill({ L, c, children }){
  return <span className="tag tag--gray" style={{background:"var(--card-gray)",color:"var(--gray)",paddingLeft:8}}>
    <span style={{width:18,height:18,borderRadius:"50%",border:`1.6px solid ${c}`,color:c,fontSize:11,fontWeight:700,display:"inline-flex",alignItems:"center",justifyContent:"center"}}>{L}</span>{children}
  </span>;
}

/* ---------- Overview ---------- */
function WeightScreen({ go }){
  const [range,setRange]=useState("6м");
  return (
    <div className="screen screen--plain screen-enter">
      <StatusBar/>
      <WHeader go={go}/>
      <WTitle/>
      <div style={{padding:"16px 18px 0",display:"flex",flexDirection:"column",gap:14}}>
        <div className="card" style={{background:"var(--ai-soft)",boxShadow:"none",padding:18,display:"flex",gap:12}}>
          <Icon.sparkle s={20} style={{color:"var(--green)",flex:"none",marginTop:2}}/>
          <div>
            <div style={{fontWeight:700,fontSize:15,color:"var(--ink)"}}>AI-комментарий</div>
            <div className="muted" style={{fontSize:15,fontWeight:500,marginTop:3,lineHeight:1.4}}>Вес менялся незначительно. После эпизода аллергии в апреле динамика стабилизировалась.</div>
          </div>
        </div>

        <div className="card" style={{display:"flex",padding:"20px 22px"}}>
          <div style={{flex:1,borderRight:"1px solid var(--line)"}}>
            <div className="muted" style={{fontSize:15,fontWeight:600}}>Текущий вес</div>
            <div style={{fontSize:34,fontWeight:800,letterSpacing:"-.02em",marginTop:2}}>28 <span style={{fontSize:20,color:"var(--gray)"}}>кг</span></div>
            <div style={{marginTop:8}}><Tag><Icon.checkC s={15}/> в пределах нормы</Tag></div>
          </div>
          <div style={{flex:1,paddingLeft:20}}>
            <div className="muted" style={{fontSize:15,fontWeight:600}}>Изменение</div>
            <div style={{fontSize:34,fontWeight:800,letterSpacing:"-.02em",marginTop:2,color:"var(--green)"}}>−1,2 <span style={{fontSize:20}}>кг</span></div>
            <div className="muted" style={{fontSize:14,fontWeight:500,marginTop:8}}>за 6 месяцев</div>
          </div>
        </div>

        <Segmented value={range} onChange={setRange}/>

        <div className="card" style={{padding:"18px 14px 14px"}}>
          <WeightChart data={data6} markers={markers6} yMax={31} lastHollow/>
          <div style={{display:"flex",gap:9,marginTop:8,flexWrap:"wrap"}}>
            <LegendPill L="A" c="#F06455">аллергия</LegendPill>
            <LegendPill L="S" c="#2A6FDB">смена корма</LegendPill>
            <LegendPill L="V" c="#20A83A">приём у врача</LegendPill>
          </div>
        </div>

        <div className="card" style={{padding:"8px 18px"}}>
          <div style={{fontSize:18,fontWeight:700,padding:"12px 0 4px"}}>Ключевые события</div>
          {[["A","#F06455","12 апр","аллергия"],["S","#2A6FDB","20 апр","смена корма"],["V","#20A83A","05 мая","контроль у врача"]].map((e,i)=>(
            <button key={i} onClick={()=>go("weight2")} className="tap" style={{display:"flex",alignItems:"center",gap:13,width:"100%",padding:"13px 0",borderTop:"1px solid var(--line)",textAlign:"left"}}>
              <span style={{width:30,height:30,borderRadius:"50%",border:`1.8px solid ${e[1]}`,color:e[1],fontSize:14,fontWeight:700,display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none"}}>{e[0]}</span>
              <span style={{fontSize:15,fontWeight:600,width:64,flex:"none"}}>{e[2]}</span>
              <span style={{fontSize:16,fontWeight:600,flex:1}}>{e[3]}</span>
              <Icon.chevR s={18} style={{color:"var(--gray)"}}/>
            </button>
          ))}
        </div>
      </div>
      <div style={{height:24}}/>
      <div className="homebar"/>
    </div>
  );
}
window.WeightScreen = WeightScreen;

/* ---------- Detail ---------- */
function WeightDetailScreen({ go }){
  const [range,setRange]=useState("1г");
  return (
    <div className="screen screen--plain screen-enter">
      <StatusBar/>
      <WHeader go={go}/>
      <WTitle/>
      <div style={{padding:"16px 18px 0",display:"flex",flexDirection:"column",gap:14}}>
        <Segmented value={range} onChange={setRange}/>

        <div className="card" style={{padding:"18px 14px 14px",position:"relative"}}>
          <div style={{position:"absolute",right:24,top:36,background:"#fff",borderRadius:14,boxShadow:"var(--shadow-card)",padding:"8px 12px",display:"flex",alignItems:"center",gap:10,zIndex:3}}>
            <div className="col">
              <span style={{fontSize:12,color:"var(--gray)",fontWeight:600}}>12 апр</span>
              <span style={{fontSize:16,fontWeight:800}}>27,4 <span style={{fontSize:12,color:"var(--gray)"}}>кг</span></span>
            </div>
            <Icon.chevR s={16} style={{color:"var(--gray)"}}/>
          </div>
          <WeightChart data={data12} markers={markers12} yMax={33} openIdx={9} lastHollow/>
        </div>

        <div className="card" style={{padding:20}}>
          <div style={{display:"flex",alignItems:"center",gap:10}}>
            <span style={{width:30,height:30,borderRadius:"50%",border:"1.8px solid #F06455",color:"#F06455",fontSize:14,fontWeight:700,display:"inline-flex",alignItems:"center",justifyContent:"center"}}>A</span>
            <span style={{fontSize:19,fontWeight:700}}>12 апреля · аллергия</span>
          </div>
          <div style={{display:"flex",marginTop:14}}>
            <div style={{flex:1}}>
              <div className="muted" style={{fontSize:14,fontWeight:600}}>Вес в этот день</div>
              <div style={{fontSize:26,fontWeight:800,marginTop:2}}>27,4 <span style={{fontSize:16,color:"var(--gray)"}}>кг</span></div>
            </div>
            <div style={{flex:1.2}}>
              <div className="muted" style={{fontSize:14,fontWeight:600}}>Примечание</div>
              <div style={{fontSize:15,fontWeight:600,marginTop:4,lineHeight:1.3}}>снижение аппетита, зуд</div>
            </div>
          </div>
          <div className="muted" style={{fontSize:14,fontWeight:600,marginTop:18}}>Связанные события</div>
          <div className="col" style={{gap:10,marginTop:10}}>
            <div style={{display:"flex",alignItems:"center",gap:11,fontSize:15,fontWeight:500,color:"var(--ink)"}}><Icon.stetho s={20} style={{color:"#7A5BD9"}}/> приём у дерматолога</div>
            <div style={{display:"flex",alignItems:"center",gap:11,fontSize:15,fontWeight:500,color:"var(--ink)"}}><Icon.bowl s={20} style={{color:"#D9A526"}}/> элиминационная диета</div>
            <div style={{display:"flex",alignItems:"center",gap:11,fontSize:15,fontWeight:500,color:"var(--ink)"}}><Icon.checkC s={20} style={{color:"var(--green)"}}/> улучшение через 2 недели</div>
          </div>
        </div>

        <div className="card" style={{background:"var(--ai-soft)",boxShadow:"none",padding:18,display:"flex",gap:12}}>
          <Icon.sparkle s={20} style={{color:"var(--green)",flex:"none",marginTop:2}}/>
          <div>
            <div style={{fontWeight:700,fontSize:15}}>AI-комментарий</div>
            <div className="muted" style={{fontSize:15,fontWeight:500,marginTop:3,lineHeight:1.4}}>Небольшое снижение веса совпало с эпизодом аллергии. После лечения вес постепенно стабилизировался.</div>
          </div>
        </div>
      </div>
      <div style={{height:16}}/>
      <div className="dock"><button className="btn btn--ghost" style={{border:"1.5px solid var(--green)",color:"var(--green)",boxShadow:"none",gap:8}} onClick={()=>go("weight")}><Icon.plus s={20}/> Добавить измерение</button></div>
      <div className="homebar"/>
    </div>
  );
}
window.WeightDetailScreen = WeightDetailScreen;
