// screens.jsx — WEB app screens (responsive, real photo, real data).
// Reuses primitives from ui.jsx: useTheme, Card, Btn, Ico, Ring, MacroBar, Pill, Seg, Photo, Divider
// Exports: HomeWeb, AnalyzingWeb, ResultWeb, AdviceWeb, AppHeader, computeBudget, SAMPLE

const SAMPLE = {
  dish: '麻辣香锅', confidence: 92, kcal: 820,
  macros: [
    { label: '碳水', grams: 62, pct: 30, key: 'carb' },
    { label: '蛋白质', grams: 38, pct: 19, key: 'protein' },
    { label: '脂肪', grams: 46, pct: 51, key: 'fat' },
  ],
  items: [
    { n: '午餐肉', k: 180 }, { n: '宽粉', k: 150 }, { n: '香辛红油', k: 200 },
    { n: '基围虾', k: 95 }, { n: '藕片 / 土豆', k: 120 }, { n: '西兰花', k: 35 },
  ],
  run: 42, steps: 11000,
};

function computeBudget(p, mode) {
  const w = p.weight, h = p.height, age = 26;
  let bmr = p.gender === '男' ? 10*w + 6.25*h - 5*age + 5 : 10*w + 6.25*h - 5*age - 161;
  let tdee = bmr * 1.4;
  if (mode === '减脂') tdee *= 0.8; else if (mode === '增肌') tdee *= 1.12;
  return Math.round(tdee / 10) * 10;
}

const MACRO_COLORS = { carb: '#F2A93C', protein: '#46B07A', fat: '#F0594B' };
const TIP_ICON = { run: 'timer', leaf: 'leaf', oil: 'drop', water: 'drop' };
const tipColor = (t) => ({ run: t.primary, leaf: t.good, oil: t.over, water: '#5B7CFA' });

// ── header ──
function AppHeader({ onBack, title, right }) {
  const t = useTheme();
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 30,
      paddingTop: 'calc(env(safe-area-inset-top) + 12px)', paddingBottom: 12,
      background: 'rgba(255,255,255,0.82)', backdropFilter: 'blur(14px)',
      borderBottom: `1px solid ${t.line}` }}>
      <div style={{ display: 'flex', alignItems: 'center', height: 38, padding: '0 14px 0 16px' }}>
        <div style={{ width: 64, display: 'flex', alignItems: 'center' }}>
          {onBack && (
            <div className="cc-tap" onClick={onBack} style={{ width: 36, height: 36, borderRadius: 18, marginLeft: -6,
              display: 'flex', alignItems: 'center', justifyContent: 'center', background: t.soft }}>
              <Ico name="back" size={20} color={t.primary} sw={2.2} />
            </div>
          )}
        </div>
        {title ? (
          <div className="num" style={{ flex: 1, textAlign: 'center', fontFamily: t.display, fontWeight: 700, fontSize: 18, color: t.ink }}>{title}</div>
        ) : (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9 }}>
            <LogoBowl size={30} color={t.primary} dark={t.dark} steam={false} />
            <Wordmark color={t.ink} size={21} font={t.display} />
          </div>
        )}
        <div style={{ width: 64, display: 'flex', justifyContent: 'flex-end' }}>{right}</div>
      </div>
    </div>
  );
}

// ── small editors ──
function Stepper({ value, set, step = 1, unit }) {
  const t = useTheme();
  const btn = (icon, fn) => (
    <div className="cc-tap" onClick={fn} style={{ width: 34, height: 34, borderRadius: 11, background: t.bg,
      border: `1px solid ${t.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <Ico name={icon} size={16} color={t.dark} sw={2.4} /></div>
  );
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      {btn('minus', () => set(value - step))}
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', minWidth: 56 }}>
        <input className="num" value={value} inputMode="numeric" maxLength={3}
          onFocus={e => e.target.select()}
          onChange={e => { const n = parseInt(String(e.target.value).replace(/[^0-9]/g, ''), 10); set(Number.isFinite(n) ? n : 0); }}
          style={{ width: 42, textAlign: 'center', border: 'none', background: 'transparent', outline: 'none',
            fontFamily: t.display, fontWeight: 700, fontSize: 19, color: t.ink, padding: 0 }} />
        <span style={{ fontSize: 12, color: t.inkSoft, fontWeight: 500 }}>{unit}</span>
      </div>
      {btn('plus', () => set(value + step))}
    </div>
  );
}
function Row({ label, children }) {
  const t = useTheme();
  return <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', minHeight: 50 }}>
    <span style={{ fontSize: 15, color: t.ink, fontWeight: 500 }}>{label}</span>{children}</div>;
}
function SectionTitle({ children, right }) {
  const t = useTheme();
  return <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', margin: '4px 2px 10px' }}>
    <span className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 16, color: t.ink }}>{children}</span>{right}</div>;
}
function ProfileCard({ profile, setProfile }) {
  const t = useTheme();
  const set = (k, v) => setProfile({ ...profile, [k]: Math.max(1, v) });
  return (
    <Card pad={18}>
      <Row label="性别"><div style={{ width: 132 }}>
        <Seg value={profile.gender} options={['男','女']} onChange={v => setProfile({ ...profile, gender: v })} /></div></Row>
      <div style={{ height: 1, background: t.line }} />
      <Row label="身高"><Stepper value={profile.height} set={v => set('height', v)} unit="cm" /></Row>
      <div style={{ height: 1, background: t.line }} />
      <Row label="体重"><Stepper value={profile.weight} set={v => set('weight', v)} unit="kg" /></Row>
    </Card>
  );
}
function GoalCard({ mode, setMode, budget }) {
  const t = useTheme();
  const note = { '减脂': '减脂期目标：制造热量缺口，优先高蛋白、高纤维。', '增肌': '增肌期目标：热量略盈余，蛋白质与碳水充足。', '维持': '维持期目标：热量收支平衡，营养均衡。' }[mode];
  return (
    <Card pad={18}>
      <Seg value={mode} options={['减脂','增肌','维持']} onChange={setMode} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 16 }}>
        <Ring pct={100} size={70} stroke={9} color={t.primary}><Ico name="target" size={26} color={t.primary} sw={2} /></Ring>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12.5, color: t.inkSoft, marginBottom: 2 }}>每日热量预算</div>
          <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 26, color: t.ink, lineHeight: 1 }}>
            {budget}<span style={{ fontSize: 14, color: t.inkSoft, marginLeft: 4 }}>kcal</span></div>
          <div style={{ fontSize: 11.5, color: t.inkFaint, marginTop: 5, lineHeight: 1.4 }}>{note}</div>
        </div>
      </div>
    </Card>
  );
}

// ── HOME ──
function HomeWeb({ profile, setProfile, mode, setMode, onPick }) {
  const t = useTheme();
  const budget = computeBudget(profile, mode);
  const camRef = React.useRef(), albRef = React.useRef();
  const handle = (e) => { const f = e.target.files && e.target.files[0]; if (f) onPick(f); e.target.value = ''; };
  return (
    <div style={{ paddingBottom: 'calc(env(safe-area-inset-bottom) + 30px)' }}>
      <div style={{ padding: 'calc(env(safe-area-inset-top) + 22px) 20px 6px', display: 'flex', alignItems: 'center', gap: 14 }}>
        <LogoBowl size={52} color={t.primary} dark={t.dark} />
        <div><Wordmark color={t.ink} size={26} font={t.display} />
          <div style={{ fontSize: 13, color: t.inkSoft, marginTop: 4 }}>拍一拍，吃得明白</div></div>
      </div>
      <div style={{ padding: '8px 16px 0', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div>
          <SectionTitle right={<span style={{ fontSize: 12, color: t.inkFaint }}>用于估算每日预算</span>}>我的资料</SectionTitle>
          <ProfileCard profile={profile} setProfile={setProfile} />
        </div>
        <div><SectionTitle>目标模式</SectionTitle><GoalCard mode={mode} setMode={setMode} budget={budget} /></div>
        <Card pad={18} style={{ background: `linear-gradient(135deg, ${t.soft}, ${t.surface})` }}>
          <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 17, color: t.ink, marginBottom: 3 }}>这餐吃了啥？</div>
          <div style={{ fontSize: 13, color: t.inkSoft, marginBottom: 16 }}>拍张照，几秒出热量和建议</div>
          <input ref={camRef} type="file" accept="image/*" capture="environment" onChange={handle} style={{ display: 'none' }} />
          <input ref={albRef} type="file" accept="image/*" onChange={handle} style={{ display: 'none' }} />
          <Btn big icon="camera" onClick={() => camRef.current.click()}>拍照识别</Btn>
          <div style={{ height: 10 }} />
          <Btn big kind="soft" icon="image" onClick={() => albRef.current.click()}>从相册上传</Btn>
        </Card>
      </div>
    </div>
  );
}

// ── ANALYZING ──
function AnalyzingWeb({ photoUrl }) {
  const t = useTheme();
  const steps = ['正在识别食物…', '估算份量与体积…', '查询热量数据库…', '生成饮食建议…'];
  const [i, setI] = React.useState(0); const [prog, setProg] = React.useState(8);
  React.useEffect(() => {
    let p = 8; const iv = setInterval(() => {
      p = Math.min(92, p + 3 + Math.random() * 5); setProg(p);
      setI(Math.min(steps.length - 1, Math.floor(p / 24)));
    }, 280); return () => clearInterval(iv);
  }, []);
  const corner = (s) => <div style={{ position: 'absolute', width: 30, height: 30, ...s }} />;
  return (
    <div style={{ minHeight: '100dvh', background: '#15110C', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 'calc(env(safe-area-inset-top) + 18px)', left: 20, color: '#fff', fontFamily: t.display, fontWeight: 700, fontSize: 17 }}>识别中</div>
      <div style={{ position: 'absolute', top: 130, left: 24, right: 24, height: 360, borderRadius: 28, overflow: 'hidden' }}>
        <img src={photoUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.22)' }} />
        <div style={{ position: 'absolute', left: 0, right: 0, height: 3, background: t.primary, boxShadow: `0 0 18px 4px ${t.primary}`, animation: 'ccScan 1.9s ease-in-out infinite alternate' }} />
        {corner({ top: 14, left: 14, borderTop: '3px solid #fff', borderLeft: '3px solid #fff', borderRadius: '10px 0 0 0' })}
        {corner({ top: 14, right: 14, borderTop: '3px solid #fff', borderRight: '3px solid #fff', borderRadius: '0 10px 0 0' })}
        {corner({ bottom: 14, left: 14, borderBottom: '3px solid #fff', borderLeft: '3px solid #fff', borderRadius: '0 0 0 10px' })}
        {corner({ bottom: 14, right: 14, borderBottom: '3px solid #fff', borderRight: '3px solid #fff', borderRadius: '0 0 10px 0' })}
      </div>
      <div style={{ position: 'absolute', top: 530, left: 0, right: 0, display: 'flex', justifyContent: 'center' }}>
        <div style={{ animation: 'ccBob 1.4s ease-in-out infinite' }}><LogoBowl size={56} color={t.primary} dark={t.dark} /></div>
      </div>
      <div style={{ position: 'absolute', top: 616, left: 36, right: 36, textAlign: 'center' }}>
        <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 20, color: '#fff' }}>{steps[i]}</div>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 14 }}>
          {[0,1,2].map(d => <span key={d} style={{ width: 7, height: 7, borderRadius: 9, background: t.primary, animation: `ccDot 1.1s ease-in-out ${d*0.18}s infinite` }} />)}
        </div>
      </div>
      <div style={{ position: 'absolute', bottom: 'calc(env(safe-area-inset-bottom) + 70px)', left: 36, right: 36 }}>
        <div style={{ height: 7, borderRadius: 9, background: 'rgba(255,255,255,0.14)', overflow: 'hidden' }}>
          <div style={{ height: '100%', width: prog + '%', background: t.primary, borderRadius: 9, transition: 'width .3s ease' }} /></div>
      </div>
    </div>
  );
}

// ── RESULT (variant A) ──
function ResultWeb({ data, mode, budget, photoUrl, demo, onAdvice, onBack, onReshoot }) {
  const t = useTheme();
  const pct = Math.round((data.kcal / budget) * 100);
  const over = pct > 45;
  const showItems = data.items && data.items.length > 0;
  return (
    <div style={{ minHeight: '100dvh' }}>
      <AppHeader title="分析结果" onBack={onBack} right={demo ? <Pill style={{ fontSize: 11 }} color={t.warn} bg={t.warn + '22'}>演示</Pill> : null} />
      <div style={{ padding: '14px 16px calc(env(safe-area-inset-bottom) + 40px)', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Card pad={16}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 56, height: 56, borderRadius: 16, overflow: 'hidden', flexShrink: 0, background: t.soft }}>
              {photoUrl ? <img src={photoUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : null}
            </div>
            <div style={{ flex: 1 }}>
              <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 19, color: t.ink }}>{data.dish}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 5 }}>
                <Pill color={t.good} bg={t.good + '22'}><span style={{ width: 6, height: 6, borderRadius: 9, background: t.good }} />识别 {data.confidence}%</Pill>
              </div>
            </div>
            <div className="cc-tap" onClick={onReshoot} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
              <Ico name="camera" size={20} color={t.primary} sw={2} /><span style={{ fontSize: 11, color: t.inkSoft }}>重拍</span>
            </div>
          </div>
        </Card>
        <Card pad={18} style={{ background: `linear-gradient(135deg, ${t.soft}, ${t.surface})` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <Ring pct={pct} size={120} stroke={13} color={over ? t.warn : t.primary}>
              <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 34, color: t.ink, lineHeight: 1 }}>{data.kcal}</div>
              <div className="num" style={{ color: t.inkSoft, fontSize: 12, fontWeight: 600 }}>kcal</div>
            </Ring>
            <div style={{ flex: 1 }}>
              <Pill color={over ? t.over : t.good} bg={(over ? t.over : t.good) + '1f'}>{over ? '占比偏高' : '热量适中'}</Pill>
              <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 17, color: t.ink, marginTop: 10, lineHeight: 1.3 }}>约占今日预算 {pct}%</div>
              <div style={{ fontSize: 12.5, color: t.inkSoft, marginTop: 4 }}>预算 {budget} kcal · {mode}模式</div>
            </div>
          </div>
        </Card>
        <Card pad={18}>
          <SectionTitle>三大营养素</SectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {data.macros.map(m => <MacroBar key={m.key} label={m.label} grams={m.grams} pct={m.pct} color={MACRO_COLORS[m.key] || t.primary} />)}
          </div>
        </Card>
        {showItems && (
          <Card pad={18}>
            <SectionTitle right={<span style={{ fontSize: 12, color: t.inkFaint }}>共 {data.items.length} 项</span>}>食材热量拆解</SectionTitle>
            {data.items.map((it, idx) => {
              const max = Math.max(...data.items.map(x => x.k));
              return (
                <div key={idx} style={{ padding: '9px 0', borderBottom: idx === data.items.length - 1 ? 'none' : `1px solid ${t.line}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
                    <span style={{ fontSize: 14, color: t.ink, fontWeight: 500 }}>{it.n}</span>
                    <span className="num" style={{ fontFamily: t.display, fontWeight: 600, fontSize: 14, color: t.dark }}>{it.k} kcal</span>
                  </div>
                  <div style={{ height: 6, borderRadius: 6, background: t.bg, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: (it.k / max * 100) + '%', background: t.primary, opacity: .75, borderRadius: 6 }} />
                  </div>
                </div>
              );
            })}
          </Card>
        )}
        <div style={{ display: 'flex', gap: 12 }}>
          <Card pad={15} style={{ flex: 1 }}>
            <Ico name="timer" size={22} color={t.primary} sw={2} />
            <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 20, color: t.ink, marginTop: 8 }}>{data.run}<span style={{ fontSize: 12, color: t.inkSoft }}> 分钟</span></div>
            <div style={{ fontSize: 12, color: t.inkSoft, marginTop: 2 }}>慢跑可抵消</div>
          </Card>
          <Card pad={15} style={{ flex: 1 }}>
            <Ico name="flame" size={22} color={t.over} sw={1.6} fill={t.over + '22'} />
            <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 20, color: t.ink, marginTop: 8 }}>{(data.steps/1000).toFixed(0)}k<span style={{ fontSize: 12, color: t.inkSoft }}> 步</span></div>
            <div style={{ fontSize: 12, color: t.inkSoft, marginTop: 2 }}>或步行抵消</div>
          </Card>
        </div>
        <Card tap onClick={onAdvice} pad={18} style={{ background: t.ink }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 14, background: 'rgba(255,255,255,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Ico name="spark" size={24} color={t.primary} sw={2} fill={t.primary} /></div>
            <div style={{ flex: 1 }}>
              <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 16, color: '#fff' }}>{data.verdict.title}</div>
              <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,.6)', marginTop: 3 }}>点开看专属饮食建议 →</div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}

// ── ADVICE ──
function AdviceWeb({ data, mode, onBack, onLog }) {
  const t = useTheme();
  const tc = tipColor(t);
  return (
    <div style={{ minHeight: '100dvh' }}>
      <AppHeader title="饮食小贴士" onBack={onBack} />
      <div style={{ padding: '14px 16px calc(env(safe-area-inset-bottom) + 40px)', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Card pad={20} style={{ background: `linear-gradient(135deg, ${t.primary}, ${t.dark})`, border: 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ animation: 'ccBob 2s ease-in-out infinite' }}><LogoFace size={52} color="#fff" bg={t.primary} feat={t.primary} /></div>
            <div style={{ flex: 1 }}>
              <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 19, color: '#fff', lineHeight: 1.3 }}>{data.verdict.title}</div>
              <div style={{ fontSize: 13, color: 'rgba(255,255,255,.88)', marginTop: 6, lineHeight: 1.5 }}>{data.verdict.sub}</div>
            </div>
          </div>
        </Card>
        <Pill style={{ alignSelf: 'flex-start', fontSize: 12.5 }} color={t.dark} bg={t.soft}>
          <Ico name="target" size={14} color={t.dark} sw={2.2} />{mode}模式
        </Pill>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {data.tips.map((tip, i) => (
            <Card key={i} pad={16}>
              <div style={{ display: 'flex', gap: 14 }}>
                <div style={{ width: 42, height: 42, borderRadius: 13, flexShrink: 0, background: (tc[tip.icon] || t.primary) + '1c', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Ico name={TIP_ICON[tip.icon] || 'spark'} size={22} color={tc[tip.icon] || t.primary} sw={2} /></div>
                <div style={{ flex: 1 }}>
                  <div className="num" style={{ fontFamily: t.display, fontWeight: 700, fontSize: 15, color: t.ink }}>{tip.t}</div>
                  <div style={{ fontSize: 13, color: t.inkSoft, marginTop: 4, lineHeight: 1.6 }}>{tip.d}</div>
                </div>
              </div>
            </Card>
          ))}
        </div>
        {data.nextMeal && data.nextMeal.length > 0 && (
          <Card pad={18}>
            <SectionTitle>下一餐这样配 🍽️</SectionTitle>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {data.nextMeal.map(n => <span key={n} className="num" style={{ padding: '9px 14px', borderRadius: 999, background: t.bg, border: `1px solid ${t.line}`, fontSize: 13.5, fontWeight: 600, color: t.ink, fontFamily: t.display }}>{n}</span>)}
            </div>
          </Card>
        )}
        <Btn big kind="dark" icon="check" onClick={onLog}>再拍一张</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { HomeWeb, AnalyzingWeb, ResultWeb, AdviceWeb, AppHeader, computeBudget, SAMPLE, MACRO_COLORS });
