// Screens, part 1: Login/landing, Skanna, Camera+AI, Resultat (low-conf), Scan-detail.
// All use chrome from components.jsx and tokens from tokens.css.
const { fmtDate, fmtDateShort, fmtNum, fmtInt, daysSince } = window;

const ICON = {
  camera: <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="2" y="4" width="14" height="11"/><circle cx="9" cy="9.5" r="3.2"/><path d="M6 4l1-1.5h4l1 1.5"/></svg>,
  upload: <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M7 1v9M3 5l4-4 4 4M2 12h10"/></svg>,
  arrow:  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M2 6h8M7 2l4 4-4 4"/></svg>,
  back:   <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M8 2L3 7l5 5"/></svg>,
  check:  <svg width="11" height="9" viewBox="0 0 11 9" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M1 5l3 3 6-7"/></svg>,
  close:  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M2 2l8 8M10 2l-8 8"/></svg>,
};

// ─── 0. LOGIN / LANDING ────────────────────────────────────────────
function ScreenLogin({ onContinue }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--paper)', position: 'relative' }}>
      <StatusBar/>

      <div style={{ flex: 1, padding: '40px 22px 0' }}>
        <div className="ib-mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', color: 'var(--ink)' }}>
          <span style={{ color: 'var(--accent)' }}>●</span> <TenantWordmark/>
        </div>
        <div className="ib-eyebrow" style={{ marginTop: 4 }}>InBody-arkiv</div>

        <div style={{ marginTop: 80 }}>
          <h1 className="ib-h1" style={{ fontSize: 38, margin: 0, marginBottom: 18 }}>
            Ditt InBody-papper, <em style={{ color: 'var(--accent)', fontStyle: 'italic' }}>i arkivet</em>.
          </h1>
          <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--ink-soft)', margin: 0, fontFamily: 'var(--sans)' }}>
            Fotografera pappret. Vi tolkar siffrorna och visar hur du utvecklas över månader och år.
          </p>
        </div>

        <div style={{ marginTop: 64 }}>
          <div className="ib-eyebrow" style={{ marginBottom: 12 }}>Logga in</div>
          <div style={{ borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)' }}>
            <div style={{ padding: '14px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
              <span className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-mute)', width: 64 }}>E-POST</span>
              <input defaultValue="gustav.b@example.se" style={{ flex: 1, border: 'none', background: 'transparent', fontFamily: 'var(--mono)', fontSize: 14, color: 'var(--ink)', outline: 'none', padding: 0 }}/>
            </div>
          </div>
          <p style={{ fontSize: 11, color: 'var(--ink-mute)', lineHeight: 1.5, marginTop: 12 }}>
            Vi mejlar en länk som loggar in dig. Ingen lösenord — länken gäller i 15 minuter.
          </p>
        </div>
      </div>

      <div style={{ padding: '20px 22px 32px' }}>
        <button className="ib-btn" style={{ width: '100%', padding: '18px' }} onClick={onContinue}>
          Skicka inloggningslänk {ICON.arrow}
        </button>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14 }}>
          <span className="ib-mono" style={{ fontSize: 9, color: 'var(--ink-mute)', letterSpacing: '0.06em' }}>
            INBODY/v2026-05
          </span>
          <a className="ib-mono" style={{ fontSize: 9, color: 'var(--ink-mute)', letterSpacing: '0.06em', textDecoration: 'underline' }}>OM TJÄNSTEN</a>
        </div>
      </div>
    </div>
  );
}

// ─── 1. SKANNA — entry view, with previous scan as reference ─────────
function ScreenSkanna({ onScan, onNav, embed }) {
  const last = window.LATEST_SCAN;
  const days = daysSince(last.scan_date);
  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--paper)', position: 'relative' }} className="ib-noscroll">
      {!embed && <StatusBar/>}
      <PageChrome section="01 · UPPLADDNING" fileId={`MEM/${MEMBER.subject_label.replace(/[^A-Z]/gi,'').slice(0,3).toUpperCase()}`} embed={embed}/>

      <TitleBlock
        eyebrow={`God morgon, ${MEMBER.subject_label.split(' ')[0]}`}
        num="01"
        title={<>Det är <em style={{ color: 'var(--accent)', fontStyle: 'italic' }}>{days} dagar</em> sedan din senaste mätning.</>}
        sub="Fotografera ditt InBody-pappersark så lägger vi värdena i ditt arkiv."
      />

      {/* Reference card — last scan as a footnote / set */}
      <SectionHead num="01.1" title="Förra mätningen" right={<span className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>{fmtDateShort(last.scan_date)}</span>}/>
      <div style={{ padding: '4px 22px 20px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14, padding: '8px 0 4px' }}>
          {[
            ['Vikt',    last.weight, 'kg'],
            ['Muskel',  last.skeletal_muscle_mass, 'kg'],
            ['Fett',    last.body_fat_percent, '%'],
          ].map(([l,v,u]) => (
            <div key={l}>
              <div className="ib-eyebrow" style={{ fontSize: 9, marginBottom: 5 }}>{l}</div>
              <div className="ib-num ib-serif" style={{ fontSize: 26, fontWeight: 400, lineHeight: 1, letterSpacing: -0.4 }}>{v}<span style={{ fontSize: 11, color: 'var(--ink-mute)', marginLeft: 3, fontFamily: 'var(--mono)', fontWeight: 500 }}>{u}</span></div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--rule-soft)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-mute)' }}>InBody-poäng</span>
          <span className="ib-num ib-serif" style={{ fontSize: 16, color: 'var(--accent)' }}>{last.inbody_score}<span style={{ fontSize: 10, color: 'var(--ink-mute)', marginLeft: 3, fontFamily: 'var(--mono)' }}>/100</span></span>
        </div>
      </div>

      {/* Primary CTA */}
      <div style={{ padding: '12px 22px 24px', borderTop: '1px solid var(--rule)' }}>
        <button className="ib-btn" style={{ width: '100%', padding: '20px' }} onClick={onScan}>
          {ICON.camera} Fotografera papperet
        </button>
        <button className="ib-btn ib-btn-ghost" style={{ width: '100%', marginTop: 10, padding: '14px' }}>
          {ICON.upload} Välj från bibliotek
        </button>
        <p className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-mute)', lineHeight: 1.5, textAlign: 'center', marginTop: 16, letterSpacing: '0.04em' }}>
          STÄLL PAPPRET PÅ JÄMN BAKGRUND · UNDVIK BLANK
        </p>
      </div>

      <div style={{ height: 100 }}/>
      <TabBar active="scan" onNav={onNav} embed={embed}/>
    </div>
  );
}

// Empty state variant — first-ever user
function ScreenSkannaEmpty({ onScan, onNav, embed }) {
  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--paper)', position: 'relative' }} className="ib-noscroll">
      {!embed && <StatusBar/>}
      <PageChrome section="01 · UPPLADDNING" fileId="MEM/—" embed={embed}/>
      <TitleBlock
        eyebrow="Välkommen, Gustav"
        num="01"
        title={<>Inga mätningar <em style={{ color: 'var(--ink-soft)', fontStyle: 'italic' }}>än</em>.</>}
        sub="Lägg in din första InBody-mätning. När du har två kan vi börja visa utveckling."
      />
      <div style={{ padding: '8px 22px 24px' }}>
        <div style={{ padding: '32px 24px', border: '1px solid var(--rule)', textAlign: 'center', background: 'var(--paper-2)' }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 48, color: 'var(--ink-faint)', lineHeight: 1, fontWeight: 300 }}>0</div>
          <div className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-soft)', marginTop: 8, letterSpacing: '0.08em' }}>MÄTNINGAR I ARKIVET</div>
        </div>
      </div>
      <div style={{ padding: '0 22px' }}>
        <button className="ib-btn" style={{ width: '100%', padding: '20px' }} onClick={onScan}>{ICON.camera} Lägg till första mätningen</button>
      </div>
      <TabBar active="scan" onNav={onNav} embed={embed}/>
    </div>
  );
}

// ─── 2. KAMERA + ANALYSERAR ─────────────────────────────────────────
function ScreenCamera({ onCapture, onCancel }) {
  return (
    <div style={{ height: '100%', background: '#0a0908', color: '#fff', position: 'relative', overflow: 'hidden' }}>
      <StatusBar/>
      <div style={{ position: 'absolute', top: 14, right: 22, zIndex: 2 }}>
        <button onClick={onCancel} style={{ width: 32, height: 32, border: '1px solid rgba(255,255,255,0.4)', background: 'rgba(0,0,0,0.4)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{ICON.close}</button>
      </div>

      {/* Viewfinder — page-shaped frame with corner ticks */}
      <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '70px 36px 220px' }}>
        <div style={{ width: '100%', aspectRatio: '210 / 297', position: 'relative', background: 'rgba(244,240,232,0.04)', borderRadius: 18, overflow: 'visible' }}>
          {/* mock paper preview lines */}
          <div style={{ position: 'absolute', inset: '14% 12% 8%', display: 'flex', flexDirection: 'column', gap: 9, opacity: 0.18 }}>
            {[1,1,1,0.6,1,1,0.7,1,1,1,0.5,1].map((w,i)=><div key={i} style={{ height: 5, width: `${w*100}%`, background: '#f4f0e8' }}/>)}
          </div>
          {/* corner ticks — bigger, accent-colored, animated */}
          {[
            { top: -2, left: -2, br: 'top left',     borders: { borderTop: '3px solid var(--accent)', borderLeft: '3px solid var(--accent)', borderTopLeftRadius: 14 } },
            { top: -2, right: -2, br: 'top right',   borders: { borderTop: '3px solid var(--accent)', borderRight: '3px solid var(--accent)', borderTopRightRadius: 14 } },
            { bottom: -2, left: -2, br: 'bottom left',  borders: { borderBottom: '3px solid var(--accent)', borderLeft: '3px solid var(--accent)', borderBottomLeftRadius: 14 } },
            { bottom: -2, right: -2, br: 'bottom right', borders: { borderBottom: '3px solid var(--accent)', borderRight: '3px solid var(--accent)', borderBottomRightRadius: 14 } },
          ].map((p, i) => (
            <div key={i} style={{ position: 'absolute', width: 32, height: 32, top: p.top, bottom: p.bottom, left: p.left, right: p.right, ...p.borders, animation: 'cornerPulse 2.4s ease-in-out infinite', animationDelay: `${i * 0.15}s` }}/>
          ))}
          {/* center reticle dot */}
          <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)', boxShadow: '0 0 0 6px rgba(255,107,61,0.18), 0 0 0 14px rgba(255,107,61,0.08)' }}/>
        </div>
      </div>

      {/* Hint pill — M3 expressive, animates */}
      <div style={{ position: 'absolute', top: 60, left: 0, right: 0, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 10,
          padding: '12px 20px 12px 14px',
          background: 'rgba(15,18,24,0.78)',
          backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
          borderRadius: 999,
          boxShadow: '0 8px 24px rgba(0,0,0,0.35), 0 0 0 1px rgba(255,255,255,0.08) inset',
          animation: 'hintBob 3.2s ease-in-out infinite',
        }}>
          <span style={{
            width: 22, height: 22, borderRadius: 999,
            background: 'var(--accent)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 11, fontWeight: 700,
            boxShadow: '0 0 0 4px rgba(255,107,61,0.25)',
          }}>◎</span>
          <span className="ib-mono" style={{ fontSize: 10.5, letterSpacing: '0.08em', color: '#fff', textTransform: 'uppercase', fontWeight: 600 }}>
            Rikta in pappret
          </span>
        </div>
      </div>

      {/* Keyframes injected once per render — cheap and isolated */}
      <style>{`
        @keyframes cornerPulse {
          0%, 100% { opacity: 1; }
          50%      { opacity: 0.55; }
        }
        @keyframes hintBob {
          0%, 100% { transform: translateY(0); }
          50%      { transform: translateY(-3px); }
        }
      `}</style>

      {/* shutter */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '24px 22px 40px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onCancel} className="ib-mono" style={{ background: 'transparent', border: 'none', color: 'rgba(255,255,255,0.7)', fontSize: 11, cursor: 'pointer', letterSpacing: '0.08em' }}>AVBRYT</button>
        <button onClick={onCapture} style={{ width: 72, height: 72, borderRadius: '50%', border: '3px solid #fff', background: 'transparent', cursor: 'pointer', position: 'relative' }}>
          <div style={{ position: 'absolute', inset: 6, borderRadius: '50%', background: '#fff' }}/>
        </button>
        <button className="ib-mono" style={{ background: 'transparent', border: 'none', color: 'rgba(255,255,255,0.7)', fontSize: 11, cursor: 'pointer', letterSpacing: '0.08em' }}>BIBLIOTEK</button>
      </div>
    </div>
  );
}

// AI analyzing — minimal, quiet
function ScreenAnalyzing({ progress = 0.45, onCancel }) {
  const phases = [
    { p: 0.20, label: 'Bildkvalitet' },
    { p: 0.55, label: 'Värden' },
    { p: 0.90, label: 'Granskar' },
  ];
  const currentPhase = phases.findIndex(ph => progress < ph.p);
  const phaseLabel = (currentPhase === -1 ? phases[phases.length - 1] : phases[currentPhase]).label;

  return (
    <div style={{ height: '100%', background: 'var(--paper)', position: 'relative', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <StatusBar/>
      <PageChrome section="01.AI · TOLKNING" fileId="VISION/v3"/>

      <div style={{ flex: 1, padding: '40px 22px 0', display: 'flex', flexDirection: 'column' }}>
        <h1 className="ib-h1" style={{ fontSize: 36, margin: 0, marginBottom: 8, letterSpacing: '-0.03em' }}>
          Tolkar resultaten.
        </h1>
        <div className="ib-mono" style={{ fontSize: 11, color: 'var(--ink-soft)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
          <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', marginRight: 8, transform: 'translateY(-1px)' }}/>
          {phaseLabel}
        </div>

        {/* Single thin spinning ring, very slow. That's it. */}
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 220 }}>
          <svg width="96" height="96" viewBox="0 0 100 100" style={{ animation: 'spinSlow 2.4s linear infinite' }}>
            <circle cx="50" cy="50" r="46" fill="none" stroke="var(--rule-soft)" strokeWidth="1"/>
            <circle cx="50" cy="50" r="46" fill="none" stroke="var(--accent)" strokeWidth="2"
                    strokeDasharray="14 280" strokeLinecap="round"/>
          </svg>
        </div>

        {/* Slim progress capsule, no labels under */}
        <div style={{ alignSelf: 'center', width: 200, marginBottom: 40 }}>
          <div style={{ height: 3, background: 'var(--surface-2)', borderRadius: 999, position: 'relative', overflow: 'hidden' }}>
            <div style={{
              position: 'absolute', top: 0, left: 0, height: '100%',
              width: `${progress*100}%`,
              background: 'var(--accent)',
              borderRadius: 999,
              transition: 'width .5s cubic-bezier(.2,.9,.3,1.2)',
            }}/>
          </div>
        </div>
      </div>

      <div style={{ padding: '12px 22px 32px' }}>
        <button className="ib-btn ib-btn-text" style={{ width: '100%' }} onClick={onCancel}>Avbryt</button>
      </div>

      <style>{`
        @keyframes spinSlow { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

// ─── 3. RESULTAT — just after scan, with low_confidence flag ─────────
function ScreenResultat({ scan, onSave, onRetake, onDiscard }) {
  const s = scan || window.FRESH_SCAN_LOWCONF;
  const prev = window.LATEST_SCAN;
  const isUncertain = (k) => s.uncertain_fields && s.uncertain_fields.includes(k);
  const dW = +(s.weight - prev.weight).toFixed(1);

  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--paper)', position: 'relative' }} className="ib-noscroll">
      <StatusBar/>
      <PageChrome section="01.RES · GRANSKA" fileId={`SCAN/${s.scan_date}`}/>

      {/* Hero number */}
      <div style={{ padding: '28px 22px 16px' }}>
        <div className="ib-eyebrow" style={{ marginBottom: 8 }}><span className="ib-eyebrow-num">01.RES</span>Vikt</div>
        <div className="ib-row" style={{ alignItems: 'baseline', gap: 8 }}>
          <span className="ib-display ib-num" style={{ fontSize: 76 }}>{s.weight}</span>
          <span className="ib-mono" style={{ fontSize: 14, color: 'var(--ink-soft)' }}>kg</span>
        </div>
        <div className="ib-mono" style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 8 }}>
          {dW > 0 ? '+' : ''}{dW} kg sedan {fmtDateShort(prev.scan_date)}
        </div>
      </div>

      {/* Low-confidence editorial sidebar */}
      {s.low_confidence && (
        <div style={{ margin: '8px 22px 14px', padding: '14px 16px', background: 'var(--warn-bg)', borderLeft: '3px solid var(--warn)' }}>
          <div className="ib-eyebrow" style={{ color: 'var(--warn)', marginBottom: 6 }}>Bilden var något otydlig</div>
          <div className="ib-serif" style={{ fontSize: 13, lineHeight: 1.45, color: 'var(--ink)' }}>
            Konfidens <strong>{s.confidence_score}</strong>. {s.uncertain_fields.length} värden tolkades med låg säkerhet — märkta nedan. Du kan spara ändå eller ta om bilden.
          </div>
        </div>
      )}

      <SectionHead num="01.RES.1" title="Sammansättning"/>
      <div>
        <DataRow prefix="01" label="Skelettmuskelmassa" value={fmtNum(s.skeletal_muscle_mass)} unit="kg"/>
        <DataRow prefix="02" label="Kroppsfett" secondary="(massa)" uncertain={isUncertain('body_fat_mass')} value={fmtNum(s.body_fat_mass)} unit="kg"/>
        <DataRow prefix="03" label="Kroppsfett" secondary="(andel)" uncertain={isUncertain('body_fat_percent')} value={fmtNum(s.body_fat_percent)} unit="%"/>
        <DataRow prefix="04" label="InBody-poäng" value={s.inbody_score} unit="/100"/>
        <DataRow prefix="05" label="BMI" value={fmtNum(s.bmi)} unit=""/>
        <DataRow prefix="06" label="Total kroppsvätska" value={fmtNum(s.total_body_water)} unit="L"/>
        <DataRow prefix="07" label="Basförbränning" value={fmtInt(s.basal_metabolic_rate)} unit="kcal"/>
        <DataRow prefix="08" label="Visceralt fett" uncertain={isUncertain('visceral_fat_level')} value={s.visceral_fat_level} unit="nivå"/>
      </div>

      <div style={{ padding: '24px 22px 110px' }}>
        <button className="ib-btn" style={{ width: '100%', padding: '18px' }} onClick={onSave}>{ICON.check} Spara i mitt arkiv</button>
        <div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
          <button className="ib-btn ib-btn-ghost" style={{ flex: 1, padding: '14px' }} onClick={onRetake}>Ta om</button>
          <button className="ib-btn ib-btn-ghost" style={{ flex: 1, padding: '14px', borderColor: 'var(--ink-mute)', color: 'var(--ink-mute)' }} onClick={onDiscard}>Kasta</button>
        </div>
      </div>
    </div>
  );
}

// ─── 4. SCAN-DETAIL (from history) — full data + segmental ────────────
// Body diagram for segmental_data.
// Body diagram for segmental_data — sleek anatomical silhouette
function BodyDiagram({ seg }) {
  if (!seg) return null;

  // Single continuous human-like silhouette in a 240x320 viewBox.
  // Each region is a tinted overlay on top of a neutral base body.
  // Smooth curves, no robot blocks.
  const partPaths = {
    // Right arm (anatomical right = viewer's left)
    right_arm:
      'M 80 92 C 70 96 62 108 58 124 C 54 142 54 160 56 178 C 57 188 60 196 64 200 C 68 202 73 200 75 196 C 76 188 75 178 76 168 C 78 154 82 138 84 126 C 86 116 86 102 84 96 Z',
    left_arm:
      'M 160 92 C 170 96 178 108 182 124 C 186 142 186 160 184 178 C 183 188 180 196 176 200 C 172 202 167 200 165 196 C 164 188 165 178 164 168 C 162 154 158 138 156 126 C 154 116 154 102 156 96 Z',
    trunk:
      'M 96 70 C 110 64 130 64 144 70 L 150 96 C 154 116 154 138 152 156 L 148 174 C 146 178 142 180 138 180 L 102 180 C 98 180 94 178 92 174 L 88 156 C 86 138 86 116 90 96 Z',
    right_leg:
      'M 102 180 C 108 180 114 182 118 184 L 122 224 C 124 252 124 280 122 300 C 121 308 117 312 113 312 C 108 312 104 308 102 300 C 99 280 98 252 99 224 Z',
    left_leg:
      'M 138 180 C 132 180 126 182 122 184 L 118 224 C 116 252 116 280 118 300 C 119 308 123 312 127 312 C 132 312 136 308 138 300 C 141 280 142 252 141 224 Z',
  };

  // Label positions outside the body, anchored on each side
  const labels = [
    { key: 'right_arm', side: 'left',  x: 18,  y: 138, anchorY: 142 },
    { key: 'trunk',     side: 'right', x: 222, y: 110, anchorY: 118 },
    { key: 'left_arm',  side: 'right', x: 222, y: 168, anchorY: 168 },
    { key: 'right_leg', side: 'left',  x: 18,  y: 248, anchorY: 252 },
    { key: 'left_leg',  side: 'right', x: 222, y: 248, anchorY: 252 },
  ];
  const partAnchors = {
    right_arm: { x: 70, y: 142 },
    left_arm:  { x: 170, y: 142 },
    trunk:     { x: 120, y: 118 },
    right_leg: { x: 110, y: 252 },
    left_leg:  { x: 130, y: 252 },
  };
  const partLabels = { right_arm: 'H. arm', left_arm: 'V. arm', trunk: 'Bål', right_leg: 'H. ben', left_leg: 'V. ben' };

  const fillFor = (data) => {
    if (!data) return 'var(--surface-2)';
    const pct = (data.lean_percent || data.percent || 100);
    const intensity = Math.min(1, Math.max(0.10, (pct - 90) / 30));
    return `color-mix(in oklab, var(--accent) ${(intensity * 100).toFixed(0)}%, var(--surface-2))`;
  };

  return (
    <svg width="100%" viewBox="0 0 240 340" style={{ display: 'block', maxWidth: 320, margin: '0 auto', overflow: 'visible' }}>
      <defs>
        <filter id="softGlow" x="-10%" y="-10%" width="120%" height="120%">
          <feGaussianBlur stdDeviation="0.3"/>
        </filter>
      </defs>

      {/* Head + neck */}
      <circle cx="120" cy="36" r="18" fill="var(--surface-2)" stroke="var(--rule-soft)" strokeWidth="0.6"/>
      <path d="M 108 56 C 112 62 128 62 132 56 L 134 70 C 130 74 110 74 106 70 Z"
            fill="var(--surface-2)" stroke="var(--rule-soft)" strokeWidth="0.6"/>

      {/* Body parts — filled by intensity */}
      {Object.entries(partPaths).map(([key, d]) => (
        <path key={key}
              d={d}
              fill={fillFor(seg[key])}
              stroke="var(--rule-soft)"
              strokeWidth="0.6"
              filter="url(#softGlow)"/>
      ))}

      {/* Hairline center line (subtle anatomical guide) */}
      <line x1="120" y1="74" x2="120" y2="178" stroke="var(--rule-hair)" strokeWidth="0.6" strokeDasharray="2 3"/>

      {/* Leader dots + labels */}
      {labels.map(l => {
        const data = seg[l.key];
        const value = data && data.lean_mass != null ? data.lean_mass.toFixed(1) : '—';
        const pct = data ? Math.round(data.lean_percent || data.percent || 100) : null;
        const a = partAnchors[l.key];
        const lineX1 = l.side === 'right' ? l.x - 4 : l.x + 4;
        return (
          <g key={l.key + '-lbl'}>
            {/* leader: small accent dot on body + thin line to label */}
            <circle cx={a.x} cy={a.y} r="2.2" fill="var(--accent)"/>
            <line x1={a.x} y1={a.y} x2={lineX1} y2={l.anchorY}
                  stroke="var(--rule-soft)" strokeWidth="0.6"/>
            {/* label block */}
            <text x={l.x} y={l.y} textAnchor={l.side === 'right' ? 'start' : 'end'}
                  fontFamily="var(--mono)" fontSize="7" letterSpacing="0.08em"
                  fill="var(--ink-mute)" style={{ textTransform: 'uppercase' }}>
              {partLabels[l.key]}
            </text>
            <text x={l.x} y={l.y + 14} textAnchor={l.side === 'right' ? 'start' : 'end'}
                  fontFamily="var(--sans)" fontSize="13" fontWeight="600"
                  fill="var(--ink)">
              {value}
              <tspan fontFamily="var(--mono)" fontSize="8" fill="var(--ink-mute)" dx="2">kg</tspan>
            </text>
            {pct != null && (
              <text x={l.x} y={l.y + 26} textAnchor={l.side === 'right' ? 'start' : 'end'}
                    fontFamily="var(--mono)" fontSize="8" fontWeight="600"
                    fill="var(--accent)">
                {pct}%
              </text>
            )}
          </g>
        );
      })}
    </svg>
  );
}

function ScreenScanDetail({ scan, onBack }) {
  const s = scan || window.LATEST_SCAN;
  const seg = s.segmental_data || {};
  const hasNewSeg = seg.right_arm && 'fat_mass' in seg.right_arm;

  return (
    <div style={{ height: '100%', overflow: 'auto', background: 'var(--paper)', position: 'relative' }} className="ib-noscroll">
      <StatusBar/>

      {/* Custom chrome with back button */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 22px 12px', borderBottom: '1px solid var(--rule)' }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center', gap: 8, color: 'var(--ink)' }}>
          {ICON.back} <span className="ib-mono" style={{ fontSize: 11, letterSpacing: '0.04em' }}>UTVECKLING</span>
        </button>
        <span className="ib-mono" style={{ fontSize: 9, color: 'var(--ink-mute)', letterSpacing: '0.06em' }}>SCAN/{s.id.slice(0,8)}</span>
      </div>

      <div style={{ padding: '22px 22px 16px' }}>
        <div className="ib-eyebrow" style={{ marginBottom: 8 }}>
          {fmtDate(s.scan_date)}
          <span style={{ marginLeft: 10 }} className={`ib-tag ${s.confidence_score < 0.7 ? 'ib-tag-warn' : 'ib-tag-mute'}`}>KONF · {s.confidence_score.toFixed(2)}</span>
        </div>
        <h1 className="ib-h1" style={{ fontSize: 30, margin: 0 }}>
          <span className="ib-num">{s.weight}</span><span className="ib-mono" style={{ fontSize: 14, color: 'var(--ink-soft)', marginLeft: 4 }}>kg</span>
          <span style={{ color: 'var(--ink-mute)', fontStyle: 'italic', fontSize: 22 }}> · {s.inbody_score}</span><span className="ib-mono" style={{ fontSize: 12, color: 'var(--ink-mute)' }}>/100</span>
        </h1>
      </div>

      {/* Segmental body */}
      <SectionHead num="1" title="Segmental fördelning" right={!hasNewSeg && <span className="ib-mono" style={{ fontSize: 9, color: 'var(--ink-mute)' }}>ENDAST MUSKEL</span>}/>
      <div style={{ padding: '20px 22px 8px' }}>
        <BodyDiagram seg={seg}/>
        <p style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 12, lineHeight: 1.5, textAlign: 'center' }}>
          Mörkare = högre muskelandel jämfört med rekommenderat (100 % = balanserad).
        </p>
      </div>

      {/* Vikt & komposition */}
      <SectionHead num="2" title="Vikt & komposition"/>
      <div>
        <DataRow prefix="01" label="Vikt"                  value={fmtNum(s.weight)} unit="kg"/>
        <DataRow prefix="02" label="Skelettmuskelmassa"    value={fmtNum(s.skeletal_muscle_mass)} unit="kg"/>
        <DataRow prefix="03" label="Kroppsfett (massa)"    value={fmtNum(s.body_fat_mass)} unit="kg"/>
        <DataRow prefix="04" label="Kroppsfett (andel)"    value={fmtNum(s.body_fat_percent)} unit="%"/>
        <DataRow prefix="05" label="Mager kroppsmassa"     missing={s.lean_body_mass == null} value={fmtNum(s.lean_body_mass)} unit="kg"/>
        <DataRow prefix="06" label="BMI"                   missing={s.bmi == null} value={fmtNum(s.bmi)} unit=""/>
      </div>

      <SectionHead num="3" title="Vatten, protein, mineraler"/>
      <div>
        <DataRow prefix="07" label="Total kroppsvätska"    value={fmtNum(s.total_body_water)} unit="L"/>
        <DataRow prefix="08" label="Protein"               missing={s.protein == null} value={fmtNum(s.protein)} unit="kg"/>
        <DataRow prefix="09" label="Mineraler"             missing={s.minerals == null} value={fmtNum(s.minerals, 2)} unit="kg"/>
      </div>

      <SectionHead num="4" title="Metabolism & risk"/>
      <div>
        <DataRow prefix="10" label="InBody-poäng"          value={s.inbody_score} unit="/100"/>
        <DataRow prefix="11" label="Basförbränning"        value={fmtInt(s.basal_metabolic_rate)} unit="kcal"/>
        <DataRow prefix="12" label="Visceralt fett"        value={s.visceral_fat_level} unit="nivå"/>
      </div>

      <div style={{ padding: '24px 22px 60px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <button className="ib-btn ib-btn-ghost" style={{ padding: '14px' }}>Exportera som PDF</button>
        <button className="ib-btn ib-btn-ghost" style={{ padding: '14px', color: 'var(--bad)', borderColor: 'var(--bad)' }}>Radera den här mätningen</button>
        <p className="ib-mono" style={{ fontSize: 10, color: 'var(--ink-mute)', marginTop: 8, textAlign: 'center', letterSpacing: '0.04em', lineHeight: 1.5 }}>
          RADERING ÅNGERBAR I 30 DAGAR · DÄREFTER PERMANENT
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenLogin, ScreenSkanna, ScreenSkannaEmpty, ScreenCamera, ScreenAnalyzing, ScreenResultat, ScreenScanDetail, BodyDiagram, ICON });
