// HCG page — wraps existing HCG tool components.

function HcgPage({ tweaks }) {
  const palette = window.PALETTES[tweaks.palette] || window.PALETTES.rose;

  const [embryos, setEmbryos] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('hcg_embryos') || '1'); } catch(e) { return 1; }
  });
  const [startValue, setStartValue] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('hcg_startValue') || '25'); } catch(e) { return 25; }
  });
  const [startDay, setStartDay] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('hcg_startDay') || '9'); } catch(e) { return 9; }
  });
  const [doublingHrs, setDoublingHrs] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('hcg_doublingHrs') || '48'); } catch(e) { return 48; }
  });
  const [testDay, setTestDay] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('hcg_testDay') || '12'); } catch(e) { return 12; }
  });
  const [twins, setTwins] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('hcg_twins') || 'false'); } catch(e) { return false; }
  });
  const [actuals, setActuals] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('hcg_actuals') || '[{"day":10,"value":58},{"day":12,"value":142}]'); }
    catch(e) { return [{day:10,value:58},{day:12,value:142}]; }
  });

  React.useEffect(() => { localStorage.setItem('hcg_embryos', JSON.stringify(embryos)); }, [embryos]);
  React.useEffect(() => { localStorage.setItem('hcg_startValue', JSON.stringify(startValue)); }, [startValue]);
  React.useEffect(() => { localStorage.setItem('hcg_startDay', JSON.stringify(startDay)); }, [startDay]);
  React.useEffect(() => { localStorage.setItem('hcg_doublingHrs', JSON.stringify(doublingHrs)); }, [doublingHrs]);
  React.useEffect(() => { localStorage.setItem('hcg_testDay', JSON.stringify(testDay)); }, [testDay]);
  React.useEffect(() => { localStorage.setItem('hcg_twins', JSON.stringify(twins)); }, [twins]);
  React.useEffect(() => { localStorage.setItem('hcg_actuals', JSON.stringify(actuals)); }, [actuals]);

  const dayMax = 28;
  const valueAtTest = window.exponentialValue(startValue * embryos, startDay, testDay, doublingHrs);
  const ref = window.rangeAt(testDay, twins);
  let interpretation = { zh:'等待驗血', en:'Pending', tone:'neutral' };
  if (valueAtTest != null && ref) {
    if (valueAtTest < ref[0])      interpretation = { zh:'低於參考範圍', en:'Below ref.', tone:'low' };
    else if (valueAtTest > ref[1]) interpretation = { zh:'高於參考範圍', en:'Above ref.', tone:'high' };
    else                           interpretation = { zh:'落在正常範圍', en:'Normal range', tone:'ok' };
  }
  const toneColor = { neutral:'var(--ink-faint)', ok:'var(--sage)', low:'var(--butter)', high:'var(--rose)' }[interpretation.tone];

  const doShare = () => {
    try { navigator.clipboard?.writeText(window.location.href); } catch(e) {}
  };
  const doDownload = () => {
    const svg = document.querySelector('svg');
    if (!svg) return;
    const clone = svg.cloneNode(true);
    clone.setAttribute('xmlns','http://www.w3.org/2000/svg');
    const walk = (n) => {
      if (n.nodeType===1) {
        ['fill','stroke'].forEach(attr => {
          const v = n.getAttribute(attr);
          if (v && v.startsWith('var(')) {
            const name = v.match(/--[\w-]+/)[0];
            const resolved = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
            if (resolved) n.setAttribute(attr, resolved);
          }
        });
        n.childNodes.forEach(walk);
      }
    };
    walk(clone);
    const blob = new Blob([new XMLSerializer().serializeToString(clone)], { type:'image/svg+xml' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `hcg-curve-${new Date().toISOString().slice(0,10)}.svg`;
    a.click();
  };

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
      {/* Controls accordion on mobile */}
      <MobileAccordion title="⚙ 設定參數 Settings">
        <div style={{ display:'flex', flexDirection:'column', gap:16, padding:'0 0 8px' }}>
          <EmbryoSelector value={embryos} onChange={setEmbryos} />
          <DoublingSlider value={doublingHrs} onChange={setDoublingHrs} />
          <StartInputs startValue={startValue} startDay={startDay} onValue={setStartValue} onDay={setStartDay} />
          <TestDayPicker value={testDay} onChange={setTestDay} />
          <TwinToggle value={twins} onChange={setTwins} />
          <Divider margin="0" />
          <ActualMeasurements actuals={actuals} onChange={setActuals} startDay={startDay} />
        </div>
      </MobileAccordion>

      {/* Summary */}
      <div style={{ padding:'14px 16px 0', display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
        {[
          { zh:'驗孕日 HCG', value: window.formatVal(valueAtTest), unit:'mIU/mL', color:'var(--accent)' },
          { zh:'臨床判讀', value: interpretation.zh, unit: interpretation.en, color: toneColor },
          { zh:'翻倍週期', value: doublingHrs, unit:'hours', color:'var(--ink)' },
          { zh:'胚胎數', value: embryos, unit: twins?'twin':'single', color:'var(--ink)' },
        ].map((s,i) => (
          <div key={i} style={{
            background:'var(--card)', border:'1px solid var(--line)',
            borderRadius:10, padding:'10px 12px',
          }}>
            <div style={{ fontSize:9.5, color:'var(--ink-faint)', marginBottom:3 }}>{s.zh}</div>
            <div className="serif" style={{ fontSize:18, fontWeight:700, color:s.color, lineHeight:1 }}>{s.value}</div>
            <div className="mono" style={{ fontSize:9, color:'var(--ink-faint)', marginTop:2 }}>{s.unit}</div>
          </div>
        ))}
      </div>

      {/* Chart */}
      <div style={{ padding:'14px 16px 0' }}>
        <Card pad="14px 12px">
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8 }}>
            <div className="serif" style={{ fontSize:16, fontWeight:600 }}>HCG 曲線</div>
            <div style={{ display:'flex', gap:6 }}>
              <PillButton onClick={doDownload} icon="↓" />
              <PillButton onClick={doShare} icon="⌁" />
            </div>
          </div>
          <HcgChart
            embryos={embryos} startValue={startValue} startDay={startDay}
            doublingHrs={doublingHrs} dayMax={dayMax}
            logScale={tweaks.logScale} showBands={tweaks.showBands}
            twins={twins} actuals={actuals.filter(a=>a.value)}
            testDay={testDay} accentColor={palette.accent} accentSoft={palette.soft}
          />
          {/* Legend */}
          <div style={{
            display:'flex', gap:12, marginTop:10, flexWrap:'wrap',
            paddingTop:10, borderTop:'1px solid var(--line-soft)',
            fontSize:10.5, color:'var(--ink-soft)',
          }}>
            <LI color={palette.accent}>預估曲線</LI>
            {tweaks.showBands && <LI pattern>{twins?'雙胞胎':'單胞胎'}範圍</LI>}
            <LI color="var(--butter)" shape="circle">實際抽血</LI>
            <LI color="var(--rose)" shape="dash">驗孕日</LI>
          </div>
        </Card>
      </div>

      {/* Milestones table */}
      <div style={{ padding:'14px 16px 100px' }}>
        <HcgMilestones embryos={embryos} startValue={startValue} startDay={startDay}
          doublingHrs={doublingHrs} twins={twins} testDay={testDay} />
      </div>
    </div>
  );
}

function LI({ color, pattern, shape='line', children }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:6 }}>
      {pattern
        ? <div style={{ width:16, height:8, background:'repeating-linear-gradient(45deg,var(--sage-soft),var(--sage-soft) 3px,transparent 3px,transparent 6px)', border:'1px solid var(--sage)', borderRadius:2 }}/>
        : shape==='circle' ? <div style={{ width:8, height:8, borderRadius:'50%', background:color, border:'1.5px solid var(--ink)'}}/>
        : shape==='dash'   ? <div style={{ width:16, height:0, borderTop:`1.5px dashed ${color}`}}/>
        : <div style={{ width:16, height:2.5, background:color, borderRadius:2}}/>
      }
      <span>{children}</span>
    </div>
  );
}

function HcgMilestones({ embryos, startValue, startDay, doublingHrs, twins, testDay }) {
  const days = [startDay, startDay+2, startDay+4, testDay, testDay+2, 20, 24, 28]
    .filter((d,i,arr) => d<=28 && d>=0 && arr.indexOf(d)===i).sort((a,b)=>a-b);
  return (
    <Card pad="14px 12px">
      <SectionTitle zh="關鍵時間點" en="Milestones" />
      <div style={{ overflowX:'auto' }}>
        <table style={{ width:'100%', borderCollapse:'collapse', fontSize:11.5 }}>
          <thead>
            <tr style={{ color:'var(--ink-faint)', fontSize:9.5, letterSpacing:'0.06em', textAlign:'left' }}>
              <th style={{ padding:'6px 8px', fontWeight:400 }}>DAY</th>
              <th style={{ padding:'6px 8px', fontWeight:400 }}>預估 HCG</th>
              <th style={{ padding:'6px 8px', fontWeight:400 }}>正常範圍</th>
            </tr>
          </thead>
          <tbody>
            {days.map(d => {
              const v = window.exponentialValue(startValue*embryos, startDay, d, doublingHrs);
              const r = window.rangeAt(d, twins);
              const inRange = v!=null && r ? (v>=r[0]&&v<=r[1]) : null;
              const note = d===startDay?'起始':d===testDay?'驗孕日':d>=21?'超音波':'';
              return (
                <tr key={d} style={{ borderTop:'1px solid var(--line-soft)' }}>
                  <td style={{ padding:'9px 8px', fontFamily:"'JetBrains Mono',monospace", color:'var(--ink)', fontSize:12 }}>
                    D{d}
                    {note && <div style={{ fontSize:9, color:'var(--ink-faint)' }}>{note}</div>}
                  </td>
                  <td style={{ padding:'9px 8px', fontFamily:"'JetBrains Mono',monospace", fontWeight:600, fontSize:12 }}>
                    {v!=null ? window.formatVal(v) : '—'}
                    <span style={{ fontSize:9, color:'var(--ink-faint)', marginLeft:3 }}>mIU</span>
                  </td>
                  <td style={{ padding:'9px 8px', fontFamily:"'JetBrains Mono',monospace", color:'var(--ink-soft)', fontSize:11 }}>
                    {r ? `${window.formatVal(r[0])}–${window.formatVal(r[1])}` : '—'}
                    {inRange!=null && (
                      <span style={{
                        marginLeft:6, fontSize:9, padding:'1px 5px', borderRadius:99,
                        background: inRange?'var(--sage-soft)':'var(--rose-soft)',
                        color: inRange?'#556a52':'#8f5952',
                      }}>{inRange?'✓':'!'}</span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

function MobileAccordion({ title, children, defaultOpen }) {
  const [open, setOpen] = React.useState(defaultOpen ?? false);
  return (
    <div style={{ borderBottom:'1px solid var(--line)' }}>
      <button className="btn-reset" onClick={() => setOpen(o=>!o)} style={{
        width:'100%', padding:'14px 16px',
        display:'flex', justifyContent:'space-between', alignItems:'center',
        background:'var(--card)',
      }}>
        <span style={{ fontSize:13, fontWeight:500, color:'var(--ink)' }}>{title}</span>
        <span style={{
          fontFamily:"'JetBrains Mono',monospace", fontSize:16,
          color:'var(--ink-faint)', transform: open?'rotate(180deg)':'none', transition:'transform 0.2s',
        }}>⌄</span>
      </button>
      {open && (
        <div style={{ padding:'0 16px 16px', background:'var(--card)' }}>
          {children}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { HcgPage, MobileAccordion });
