// checkin.jsx — animated daily check-in walkthrough
// Auto-plays the 6 stages of the check-in sheet onto an iPhone, with sidebar narration.

const { useState: useCState, useEffect: useCEffect, useRef: useCRef } = React;

const STEPS = [
  { id: 'feeling',  label: 'Feeling',  italic: 'how does it feel today?', body: "Four answers: great, fine, off, rough. That's the spine of the journal — most users stop here and close the app. That is fine.", req: true },
  { id: 'flags',    label: 'Flags',    italic: 'optional · what stands out?', body: "Tap any chip that resonates. Stinging, redness, breakout, dryness, oiliness, tightness. The chips never accuse — they describe.", req: false },
  { id: 'products', label: 'Products', italic: 'optional · what did you use?', body: "Pull from your saved routine, or scan a barcode to add one. No shopping links, no purchase-logging — the point is mapping cause and effect over weeks.", req: false },
  { id: 'photo',    label: 'Photo',    italic: 'optional · a single tap', body: "Silhouette overlay and ambient light advisory. Saved on-device with complete file protection. Never uploaded by default. Never analysed by AI.", req: false },
  { id: 'notes',    label: 'Notes',    italic: 'optional · a sentence or two', body: "A small free-text field. Sometimes the most useful field. Often left empty. Also fine.", req: false },
  { id: 'save',     label: 'Save',     italic: 'and on with your day', body: "A 10-second log compounds across weeks into a quiet record of what actually moves your skin. No streaks. No notifications nagging you back.", req: true },
];

function CheckIn({ motion = true }) {
  const [step, setStep] = useCState(0);
  const [auto, setAuto] = useCState(true);

  useCEffect(() => {
    if (!motion || !auto) return;
    const id = setInterval(() => setStep((s) => (s + 1) % STEPS.length), 4200);
    return () => clearInterval(id);
  }, [motion, auto]);

  return (
    <section id="checkin" className="section" style={{
      position: 'relative',
      background: 'linear-gradient(180deg, transparent 0%, rgba(229,240,232,0.45) 30%, rgba(229,240,232,0.45) 70%, transparent 100%)',
    }}>
      <div className="container">
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 16,
          marginBottom: 'clamp(28px, 4vh, 48px)',
        }}>
          <span className="eyebrow">§ 04 · Daily check-in</span>
          <span style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
          <span className="lab">10 seconds · six layers · skippable</span>
        </div>

        <div className="checkin-head" style={{
          display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 32, alignItems: 'end',
        }}>
          <h2 className="display-3 text-balance" style={{ margin: 0 }}>
            One question. Six optional layers.{' '}
            <span className="serif-italic" style={{ color: 'var(--moss-deep)' }}>Closed in ten seconds.</span>
          </h2>
          <p className="body-l text-pretty" style={{ margin: 0 }}>
            Built for the user who answers in a blink and the user who fills every field —
            without rewarding either over the other.
          </p>
        </div>
      </div>

      <div className="container" style={{ marginTop: 'clamp(60px, 8vh, 100px)' }}>
        <div className="checkin-grid" style={{
          display: 'grid',
          gridTemplateColumns: '0.9fr 1fr',
          gap: 'clamp(40px, 5vw, 80px)',
          alignItems: 'center',
        }}>
          {/* LEFT — steps timeline */}
          <div>
            {STEPS.map((s, i) => (
              <StepRow
                key={s.id}
                idx={i}
                step={s}
                active={i === step}
                done={i < step}
                onClick={() => { setStep(i); setAuto(false); }}
              />
            ))}

            <div style={{ marginTop: 24, display: 'flex', gap: 10, alignItems: 'center' }}>
              <button
                onClick={() => { setStep((s) => Math.max(0, s - 1)); setAuto(false); }}
                className="btn btn-ghost"
                style={{ padding: '10px 14px', fontSize: 13 }}
              >← Prev</button>
              <button
                onClick={() => { setStep((s) => Math.min(STEPS.length - 1, s + 1)); setAuto(false); }}
                className="btn btn-primary"
                style={{ padding: '10px 14px', fontSize: 13 }}
              >Next →</button>
              <button
                onClick={() => setAuto(a => !a)}
                style={{
                  marginLeft: 'auto', background: 'transparent', border: 0,
                  fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: 'var(--moss-deep)', cursor: 'pointer',
                }}>
                {auto ? '⏸ pause auto' : '▶ play auto'}
              </button>
            </div>
          </div>

          {/* RIGHT — sheet on iPhone */}
          <div style={{
            position: 'relative', display: 'flex', justifyContent: 'center',
          }}>
            {/* halo */}
            <div style={{
              position: 'absolute', top: '50%', left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 460, height: 460, borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(232,184,197,0.32), transparent 65%)',
              filter: 'blur(40px)', pointerEvents: 'none',
              animation: motion ? 'breathe 7s ease-in-out infinite' : 'none',
            }} />
            <IPhone width={340} label={`step ${step + 1} / ${STEPS.length}`}>
              <CheckInSheet step={step} motion={motion} />
            </IPhone>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 1100px) {
          .checkin-grid, .checkin-head { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

function StepRow({ idx, step, active, done, onClick }) {
  return (
    <div onClick={onClick} style={{
      position: 'relative', cursor: 'pointer',
      padding: '14px 0 14px 38px',
      borderBottom: '1px solid var(--rule)',
    }}>
      {/* connector */}
      {idx < STEPS.length - 1 && (
        <div style={{
          position: 'absolute', left: 13, top: 28, bottom: -2,
          width: 1, background: done ? 'var(--moss)' : 'var(--rule)',
          transition: 'background .4s ease',
        }} />
      )}

      {/* dot */}
      <div style={{
        position: 'absolute', left: 6, top: 16,
        width: 16, height: 16, borderRadius: '50%',
        background: active ? 'var(--moss)' : (done ? 'var(--moss)' : '#FFFFFF'),
        border: `1.5px solid ${active || done ? 'var(--moss)' : 'var(--rule-strong)'}`,
        boxShadow: active ? '0 0 0 6px rgba(127,179,160,0.18)' : 'none',
        transition: 'all .35s ease',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {done && (
          <svg width="9" height="9" viewBox="0 0 10 10" fill="none">
            <path d="M2 5l2 2 4-4" stroke="#FFFFFF" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <span className="lab" style={{ color: active ? 'var(--moss-deep)' : 'var(--ink-faint)', minWidth: 28 }}>0{idx + 1}</span>
        <h3 style={{
          margin: 0, fontFamily: 'var(--font-display)', fontWeight: 400,
          fontSize: 26, lineHeight: 1.05, letterSpacing: '-0.015em',
          color: active ? 'var(--ink)' : (done ? 'var(--ink-muted)' : 'var(--ink-faint)'),
          transition: 'color .35s ease',
        }}>{step.label}</h3>
        {step.req && (
          <span className="lab" style={{
            marginLeft: 'auto',
            color: 'var(--moss-deep)',
            background: 'rgba(127,179,160,0.16)', padding: '2px 8px', borderRadius: 6,
          }}>required</span>
        )}
      </div>
      <div className="serif-italic" style={{
        fontSize: 15, marginTop: 6,
        color: active ? 'var(--moss-deep)' : 'var(--ink-faint)',
        transition: 'color .35s ease',
      }}>
        {step.italic}
      </div>

      {active && (
        <p className="body-m text-pretty" style={{
          margin: '12px 0 0', maxWidth: 480, color: 'var(--ink-soft)',
          animation: 'fade-down .5s ease both',
        }}>{step.body}</p>
      )}
      <style>{`@keyframes fade-down { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; } }`}</style>
    </div>
  );
}

/* ── Animated check-in sheet ──────────────────────────────── */
function CheckInSheet({ step, motion }) {
  const stepId = STEPS[step].id;

  return (
    <div style={{
      position: 'absolute', inset: 0, paddingTop: 0,
      background: '#F4F8F4',
      fontFamily: 'system-ui, -apple-system, sans-serif',
      color: '#1B2823',
    }}>
      {/* faint Today screen behind */}
      <div style={{ position: 'absolute', inset: 0, opacity: 0.4 }}>
        <ScreenToday motion={false} />
      </div>

      {/* sheet */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: '#FFFFFF',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        boxShadow: '0 -20px 40px -20px rgba(27,40,35,0.25)',
        padding: '12px 18px 24px',
        height: '78%',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* grab handle */}
        <div style={{ width: 38, height: 4, background: '#d4dcd7', borderRadius: 2, margin: '0 auto 14px' }} />

        {/* progress dots */}
        <div style={{ display: 'flex', gap: 5, justifyContent: 'center', marginBottom: 14 }}>
          {STEPS.map((_, i) => (
            <div key={i} style={{
              width: i === step ? 22 : 5, height: 5, borderRadius: 3,
              background: i <= step ? '#5A9985' : '#d4dcd7',
              transition: 'all .35s ease',
            }} />
          ))}
        </div>

        <h2 style={{
          fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 22, lineHeight: 1.1,
          letterSpacing: '-0.01em', margin: 0,
        }}>
          {stepId === 'feeling'  && "How's your skin today?"}
          {stepId === 'flags'    && <>Anything <i>standing out</i>?</>}
          {stepId === 'products' && "What did you use?"}
          {stepId === 'photo'    && "Care to add a photo?"}
          {stepId === 'notes'    && "Anything to note?"}
          {stepId === 'save'     && <>Saved. <i>Have a soft day.</i></>}
        </h2>

        <div style={{ marginTop: 14, flex: 1, overflow: 'hidden' }}>
          {stepId === 'feeling'  && <PaneFeeling motion={motion} />}
          {stepId === 'flags'    && <PaneFlags motion={motion} />}
          {stepId === 'products' && <PaneProducts motion={motion} />}
          {stepId === 'photo'    && <PanePhoto motion={motion} />}
          {stepId === 'notes'    && <PaneNotes motion={motion} />}
          {stepId === 'save'     && <PaneSave motion={motion} />}
        </div>

        {/* footer button */}
        <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
          <button style={{
            flex: 1, padding: '12px 0', borderRadius: 14,
            background: '#1B2823', color: '#F4F8F4', border: 0,
            fontSize: 13, fontWeight: 500,
          }}>
            {stepId === 'save' ? 'Close' : 'Save & next →'}
          </button>
        </div>
      </div>
    </div>
  );
}

function PaneFeeling({ motion }) {
  const opts = [
    { f: 'great', italic: 'calm & comfortable', col: '#B8D4C2' },
    { f: 'fine',  italic: 'unremarkable',      col: '#D9E8C9' },
    { f: 'off',   italic: 'something\'s up',   col: '#F0DCD0' },
    { f: 'rough', italic: 'struggling',        col: '#E8A89C' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {opts.map((o, i) => (
        <div key={o.f} style={{
          padding: '12px 14px', borderRadius: 14,
          background: i === 1 ? `linear-gradient(90deg, ${o.col}, #F4F8F4)` : '#F4F8F4',
          border: i === 1 ? '1px solid #5A9985' : '0.5px solid rgba(127,179,160,0.2)',
          display: 'flex', alignItems: 'center', gap: 12,
          animation: motion ? `pop-in .4s cubic-bezier(.16,.84,.32,1) ${i*0.06}s both` : 'none',
        }}>
          <div style={{ width: 26, height: 26, borderRadius: '50%', background: o.col }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 18, color: '#1B2823' }}>{o.f}</div>
            <div style={{ fontSize: 11, color: '#6b746f' }}>{o.italic}</div>
          </div>
          {i === 1 && <Check />}
        </div>
      ))}
      <style>{`@keyframes pop-in { from { opacity:0; transform: scale(.96); } to { opacity:1; transform: scale(1); } }`}</style>
    </div>
  );
}

function PaneFlags({ motion }) {
  const flags = ['stinging', 'redness', 'breakout', 'dryness', 'oiliness', 'tightness'];
  const active = ['dryness', 'tightness'];
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {flags.map((f, i) => {
        const on = active.includes(f);
        return (
          <div key={f} style={{
            padding: '8px 14px', borderRadius: 999,
            background: on ? '#5A9985' : '#F4F8F4',
            color: on ? '#FFFFFF' : '#1B2823',
            fontSize: 12, fontWeight: 500,
            border: '1px solid ' + (on ? '#5A9985' : 'rgba(127,179,160,0.3)'),
            animation: motion ? `pop-in .4s cubic-bezier(.16,.84,.32,1) ${i*0.05}s both` : 'none',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            {on && <Check small />}
            {f}
          </div>
        );
      })}
    </div>
  );
}

function PaneProducts({ motion }) {
  const prods = [
    { n: 'Niacinamide 10%',         brand: 'The Ordinary',    on: true },
    { n: 'Hydrating cleanser',      brand: 'CeraVe',          on: true },
    { n: 'Mineral SPF 50',          brand: 'Beauty of Joseon', on: false },
    { n: 'Snail mucin essence',     brand: 'COSRX',           on: false },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {prods.map((p, i) => (
        <div key={p.n} style={{
          padding: '10px 12px', borderRadius: 12,
          background: p.on ? '#E5F0E8' : '#F4F8F4',
          display: 'flex', alignItems: 'center', gap: 10,
          border: '0.5px solid rgba(127,179,160,0.2)',
          animation: motion ? `pop-in .4s ease ${i*0.06}s both` : 'none',
        }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: 'radial-gradient(circle at 30% 30%, #FFF, #D9E8C9)' }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{p.n}</div>
            <div style={{ fontSize: 10, color: '#6b746f' }}>{p.brand}</div>
          </div>
          {p.on ? <Check /> : <span style={{ width: 18, height: 18, borderRadius: '50%', border: '1.4px solid #d4dcd7' }} />}
        </div>
      ))}
    </div>
  );
}

function PanePhoto({ motion }) {
  return (
    <div style={{
      position: 'relative', height: 240, borderRadius: 14, overflow: 'hidden',
      background: 'linear-gradient(180deg, #2C3A33, #1B2823)',
    }}>
      {/* fake camera scene */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 50% 60%, rgba(232,200,150,0.18), transparent 60%)',
      }} />

      {/* silhouette overlay */}
      <svg viewBox="0 0 200 240" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <ellipse cx="100" cy="105" rx="58" ry="78" fill="none" stroke="#F4F8F4" strokeOpacity="0.55" strokeWidth="1" strokeDasharray="4 5" />
        <line x1="100" y1="30" x2="100" y2="180" stroke="#F4F8F4" strokeOpacity="0.3" strokeWidth="0.5" />
        <line x1="50" y1="105" x2="150" y2="105" stroke="#F4F8F4" strokeOpacity="0.3" strokeWidth="0.5" />
      </svg>

      {/* ambient light advisory */}
      <div style={{
        position: 'absolute', top: 10, left: 10, padding: '6px 10px',
        background: 'rgba(229,240,232,0.85)', color: '#3D6B57',
        fontSize: 10, fontFamily: 'var(--font-mono)', borderRadius: 8,
        letterSpacing: '0.12em', textTransform: 'uppercase',
      }}>
        ☀ similar light to last shot
      </div>

      {/* shutter */}
      <div style={{
        position: 'absolute', bottom: 14, left: '50%', transform: 'translateX(-50%)',
        width: 52, height: 52, borderRadius: '50%',
        background: '#F4F8F4', border: '3px solid rgba(244,248,244,0.5)',
        boxShadow: '0 0 0 4px rgba(244,248,244,0.18)',
        animation: motion ? 'breathe 1.6s ease-in-out infinite' : 'none',
      }} />
    </div>
  );
}

function PaneNotes({ motion }) {
  const text = "Tight after evening cleanse, esp. cheeks. Skipped the actives. Slept 7h.";
  return (
    <div style={{
      padding: 14, borderRadius: 14, background: '#F4F8F4',
      border: '0.5px solid rgba(127,179,160,0.2)', minHeight: 140,
      fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 17,
      color: '#1B2823', lineHeight: 1.4,
    }}>
      <TypedText text={text} motion={motion} />
      <span style={{
        display: 'inline-block', width: 2, height: 18, background: '#5A9985',
        marginLeft: 2, animation: motion ? 'caret 1s steps(2) infinite' : 'none',
        verticalAlign: 'middle',
      }} />
      <style>{`
        @keyframes caret { 50% { opacity: 0; } }
      `}</style>
    </div>
  );
}

function TypedText({ text, motion }) {
  const [n, setN] = useCState(motion ? 0 : text.length);
  useCEffect(() => {
    if (!motion) return;
    setN(0);
    let i = 0;
    const id = setInterval(() => {
      i++;
      setN(i);
      if (i >= text.length) clearInterval(id);
    }, 28);
    return () => clearInterval(id);
  }, [text, motion]);
  return <span>{text.slice(0, n)}</span>;
}

function PaneSave({ motion }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'center', height: '100%', textAlign: 'center', gap: 10,
    }}>
      <div style={{ width: 80, height: 80, position: 'relative' }}>
        <svg viewBox="0 0 100 100" width="80" height="80">
          <circle cx="50" cy="50" r="40" fill="none" stroke="#5A9985" strokeWidth="2"
            strokeDasharray="251.3"
            strokeDashoffset={motion ? 251.3 : 0}
            style={{ animation: motion ? 'draw-circ 0.8s cubic-bezier(.4,0,.2,1) forwards' : 'none', transformOrigin: 'center' }}
            transform="rotate(-90 50 50)" />
          <path d="M 32 52 L 45 64 L 68 38" fill="none" stroke="#5A9985" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
            strokeDasharray="60" strokeDashoffset={motion ? 60 : 0}
            style={{ animation: motion ? 'draw-circ 0.5s cubic-bezier(.4,0,.2,1) 0.7s forwards' : 'none' }} />
        </svg>
      </div>
      <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 16, color: '#3D6B57' }}>
        entry · added to today
      </div>
      <div style={{ fontSize: 11, color: '#6b746f', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
        on device · encrypted · yours
      </div>
      <style>{`@keyframes draw-circ { to { stroke-dashoffset: 0; } }`}</style>
    </div>
  );
}

function Check({ small }) {
  const s = small ? 12 : 16;
  return (
    <svg width={s} height={s} viewBox="0 0 16 16" fill="none">
      <circle cx="8" cy="8" r="7" fill="#5A9985" />
      <path d="M5 8l2 2 4-4" stroke="#FFFFFF" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

Object.assign(window, { CheckIn });
