/* global React, RIcons, AGENT_PERSONALITIES, ROUND_FORMATS, ONBOARD_DEFAULTS */
// Onboarding — Felt Rounds first-time setup. Introduces Rounds to new users.
// Flow: Hero → Step1 (when) → Step2 (what goes in) → Step3 (agent) → Done (ceremony)

const { useState: useStateOB, useEffect: useEffectOB } = React;

// ─── Stars ────────────────────────────────────────────────
const OB_STARS = [
  { x: 6,  y: 28,  d: 0.0 }, { x: 19, y: 95,  d: 1.3 }, { x: 33, y: 42,  d: 2.2 },
  { x: 52, y: 16,  d: 0.7 }, { x: 68, y: 78,  d: 2.9 }, { x: 83, y: 34,  d: 1.1 },
  { x: 90, y: 58,  d: 2.5 }, { x: 10, y: 66,  d: 1.8 }, { x: 44, y: 122, d: 0.5 },
  { x: 76, y: 144, d: 2.4 }, { x: 22, y: 192, d: 1.0 }, { x: 60, y: 218, d: 2.8 },
];
function OBStars({ count = 12 }) {
  return (
    <div className="nw-stars" aria-hidden="true">
      {OB_STARS.slice(0, count).map((s, i) => (
        <span key={i} style={{ left: s.x + '%', top: s.y + 'px', animationDelay: s.d + 's' }} />
      ))}
    </div>
  );
}

// ─── Shared layout pieces ─────────────────────────────────
function OBTopBar({ onBack, step, totalSteps }) {
  return (
    <div className="nw-top">
      <button className="nw-iconbtn" onClick={onBack} aria-label="Back">
        <RIcons.ChevronLeft size={20} />
      </button>
      <div className="nw-step-pill">Step {step} of {totalSteps}</div>
      <div style={{ width: 36 }} />
    </div>
  );
}

function OBProgress({ pct }) {
  return (
    <div className="ob-progress">
      <div className="ob-progress-fill" style={{ width: `${pct}%` }} />
    </div>
  );
}

function OBFooterCTA({ children }) {
  return (
    <div className="nw-footer-cta">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, position: 'relative', zIndex: 1 }}>
        {children}
      </div>
    </div>
  );
}

// ─── Time helper ──────────────────────────────────────────
function incrementTime(timeStr, deltaMinutes) {
  // Parse "H:MM AM/PM" or "HH:MM AM/PM"
  const match = timeStr.match(/^(\d+):(\d{2})\s*(AM|PM)$/i);
  if (!match) return timeStr;
  let hours = parseInt(match[1], 10);
  const mins = parseInt(match[2], 10);
  const period = match[3].toUpperCase();

  // Convert to 24h total minutes
  let total = hours * 60 + mins;
  if (period === 'AM' && hours === 12) total -= 720;
  if (period === 'PM' && hours !== 12) total += 720;

  total += deltaMinutes;

  // Wrap around 24h
  total = ((total % 1440) + 1440) % 1440;

  // Convert back
  const newHours24 = Math.floor(total / 60);
  const newMins = total % 60;
  const newPeriod = newHours24 < 12 ? 'AM' : 'PM';
  let newHours12 = newHours24 % 12;
  if (newHours12 === 0) newHours12 = 12;
  const minStr = newMins < 10 ? '0' + newMins : '' + newMins;
  return `${newHours12}:${minStr} ${newPeriod}`;
}

// Clamp a time string to [minStr, maxStr] in "H:MM AM/PM" space
function clampTime(timeStr, minStr, maxStr) {
  function toMinutes(t) {
    const m = t.match(/^(\d+):(\d{2})\s*(AM|PM)$/i);
    if (!m) return 0;
    let h = parseInt(m[1], 10);
    const mn = parseInt(m[2], 10);
    const p = m[3].toUpperCase();
    let total = h * 60 + mn;
    if (p === 'AM' && h === 12) total -= 720;
    if (p === 'PM' && h !== 12) total += 720;
    return total;
  }
  const t = toMinutes(timeStr);
  const lo = toMinutes(minStr);
  const hi = toMinutes(maxStr);
  if (t < lo) return minStr;
  if (t > hi) return maxStr;
  return timeStr;
}

// Static — hoisted so JSX elements aren't recreated on every render
const HERO_FEATURES = [
  { icon: <RIcons.ShieldCheck size={18} />, title: 'Board-certified pediatrician, nightly',  sub: 'A real FAAP doctor reviews Nora\'s overnight data and signs every report.' },
  { icon: <RIcons.TrendUp size={18} />,     title: 'Her baseline, already built',             sub: '30 nights of Owlet data — already waiting. Rounds reads what\'s already there.' },
  { icon: <RIcons.Journal size={18} />,     title: 'Journal feeds in automatically',          sub: 'Feeds, naps, meds, and temp — the doctor sees your full day context.' },
  { icon: <RIcons.Sparkles size={18} />,    title: 'Ask anything when you wake',              sub: 'Your Care Agent explains any finding the moment you open the app.' },
];

// ─── OnboardHeroScreen ────────────────────────────────────
function OnboardHeroScreen({ onStart }) {
  const features = HERO_FEATURES;

  return (
    <div className="ob-page ob-page--footer screen-enter">
      <OBStars count={12} />
      <div className="nw-aurora" />

      <div className="ob-hero-scroll">
        {/* Launch badge */}
        <div className="ob-hero-badge">
          <span className="ob-hero-badge-dot" />
          New · Morning Rounds
        </div>

        {/* Headline */}
        <h1 className="ob-hero-title">Meet your<br />Morning Round</h1>
        <p className="ob-hero-sub">
          Nora&apos;s data is already here. Now get a pediatrician to read it.
        </p>

        {/* Mini round preview — shows exactly what a round looks like */}
        <div className="ob-round-preview">
          <div className="ob-round-preview-header">
            <span className="ob-round-preview-label">Morning Round · Today</span>
            <span className="ob-round-preview-signed">
              <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              Signed
            </span>
          </div>
          <p className="ob-round-preview-quote">
            &ldquo;Nora had a quiet night. Two brief stirrings self-resolved. No action needed.&rdquo;
          </p>
          <div className="ob-round-preview-vitals">
            <span className="ob-round-preview-pill">♥ 102 bpm</span>
            <span className="ob-round-preview-pill">SpO₂ 97%</span>
            <span className="ob-round-preview-pill">10h 12m</span>
          </div>
          <div className="ob-round-preview-sig">
            <div className="ob-round-preview-ava" style={{ backgroundImage: "url('assets/doc-mehta.png')" }} />
            <div>
              <div className="ob-round-preview-signame">Dr. Anika Patel, MD, FAAP</div>
              <div className="ob-round-preview-sigtime">Pediatrician · Signed 7:31 AM</div>
            </div>
          </div>
        </div>

        {/* Feature list */}
        <div className="ob-feature-list">
          {features.map((f, i) => (
            <div key={i} className="ob-feature-row">
              <div className="ob-feature-icon">{f.icon}</div>
              <div className="ob-feature-body">
                <div className="ob-feature-title">{f.title}</div>
                <div className="ob-feature-sub">{f.sub}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Credibility */}
        <div className="ob-cred-line">MDI board-certified · FAAP pediatricians · every night</div>
      </div>

    </div>
  );
}

// ─── OnboardStep1Screen ───────────────────────────────────
function OnboardStep1Screen({ onBack, onNext, prefs, setPrefs }) {
  function adjMorning(delta) {
    setPrefs(p => ({
      ...p,
      morningTime: clampTime(incrementTime(p.morningTime, delta), '5:00 AM', '10:00 AM'),
    }));
  }
  function adjEvening(delta) {
    setPrefs(p => ({
      ...p,
      eveningTime: clampTime(incrementTime(p.eveningTime, delta), '3:00 PM', '9:00 PM'),
    }));
  }

  const hasAfternoon = prefs.frequency === 'morning_evening';

  return (
    <div className="ob-page ob-page--footer screen-enter">
      <OBStars count={8} />
      <div className="nw-aurora" />

      <div style={{ position: 'relative', zIndex: 1, padding: '16px 20px 0' }}>
        <OBTopBar onBack={onBack} step={1} totalSteps={3} />
        <OBProgress pct={33} />

        <div style={{ marginTop: 20 }}>
          <div className="ob-kicker">Delivery</div>
          <h1 className="ob-step-title">When do you want your rounds?</h1>
          <p className="ob-step-sub">Morning is always on. Add an afternoon check-in if you&apos;d like.</p>
        </div>

        {/* Round rows — glass card */}
        <div className="ob-perm-list" style={{ marginTop: 22 }}>
          {/* Row 1: Morning Round — locked, always on */}
          <div
            className="ob-perm-row"
            style={{ borderBottom: '1px solid rgba(212,212,249,0.05)' }}
          >
            <div className="ob-perm-icon"><RIcons.Sunrise size={18} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="ob-perm-label">Morning Round</div>
              <div className="ob-perm-sublabel">Always included — reviews Nora&apos;s overnight data.</div>
            </div>
            <div style={{
              padding: '3px 10px',
              borderRadius: 999,
              background: 'rgba(157,227,205,0.12)',
              border: '1px solid rgba(157,227,205,0.28)',
              color: 'var(--primary)',
              fontSize: 11,
              fontWeight: 700,
            }}>
              Always on
            </div>
          </div>

          {/* Row 2: Afternoon Round — opt-in toggle */}
          <div
            className="ob-perm-row"
            onClick={() => setPrefs(p => ({
              ...p,
              frequency: p.frequency === 'morning_evening' ? 'morning' : 'morning_evening',
            }))}
          >
            <div className="ob-perm-icon"><RIcons.Sun size={18} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="ob-perm-label">Afternoon Round</div>
              <div className="ob-perm-sublabel">A midday check-in. Optional and always free.</div>
            </div>
            <OBToggle on={hasAfternoon} />
          </div>
        </div>

        {/* Free note */}
        <div style={{ marginTop: 10, fontSize: 12, color: 'var(--foreground-muted)', textAlign: 'center' }}>
          Both rounds are always free.
        </div>

        {/* Time block(s) */}
        <div style={{ marginTop: 14 }}>
          <div className="ob-time-block">
            <div className="ob-time-label">Morning delivery</div>
            <div className="ob-time-row">
              <div className="ob-time-display">{prefs.morningTime}</div>
              <div className="ob-time-btns">
                <button className="ob-time-btn" onClick={() => adjMorning(30)} aria-label="Earlier">▲</button>
                <button className="ob-time-btn" onClick={() => adjMorning(-30)} aria-label="Later">▼</button>
              </div>
            </div>
          </div>

          {hasAfternoon && (
            <div className="ob-time-block" style={{ marginTop: 10 }}>
              <div className="ob-time-label">Afternoon delivery</div>
              <div className="ob-time-row">
                <div className="ob-time-display">{prefs.eveningTime}</div>
                <div className="ob-time-btns">
                  <button className="ob-time-btn" onClick={() => adjEvening(30)} aria-label="Earlier">▲</button>
                  <button className="ob-time-btn" onClick={() => adjEvening(-30)} aria-label="Later">▼</button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      <OBFooterCTA>
        <button className="nw-cta" onClick={() => { window.haptics?.trigger('light'); onNext(); }}>
          Continue <RIcons.ChevronRight size={18} />
        </button>
      </OBFooterCTA>
    </div>
  );
}

// ─── OnboardStep2Screen ───────────────────────────────────
const PERM_ROWS = [
  { key: 'vitals',       icon: <RIcons.Heart size={18} />,   label: 'Overnight vitals',   sub: 'Heart rate, SpO₂, movement' },
  { key: 'sleep',        icon: <RIcons.Moon size={18} />,    label: 'Sleep data',          sub: 'Duration, stretches, stirrings' },
  { key: 'journal',      icon: <RIcons.Journal size={18} />, label: "Today's journal",     sub: 'Feeds, naps, meds, temp' },
  { key: 'baseline',     icon: <RIcons.TrendUp size={18} />, label: '30-night baseline',   sub: "Nora's personal normal, already built" },
  { key: 'observations', icon: <RIcons.Note size={18} />,    label: 'Your observations',   sub: 'Anything you flag before bed' },
];

function OBToggle({ on }) {
  return (
    <div className={`ob-toggle${on ? ' on' : ''}`}>
      <div className="ob-toggle-thumb" />
    </div>
  );
}

function OnboardStep2Screen({ onBack, onNext, prefs, setPrefs }) {
  function togglePerm(key) {
    setPrefs(p => ({
      ...p,
      permissions: { ...p.permissions, [key]: !p.permissions[key] },
    }));
  }

  const selectedFormat = ROUND_FORMATS.find(f => f.id === prefs.format) || ROUND_FORMATS[0];

  return (
    <div className="ob-page ob-page--footer screen-enter">
      <OBStars count={8} />
      <div className="nw-aurora" />

      <div style={{ position: 'relative', zIndex: 1, padding: '16px 20px 0' }}>
        <OBTopBar onBack={onBack} step={2} totalSteps={3} />
        <OBProgress pct={66} />

        <div style={{ marginTop: 20 }}>
          <div className="ob-kicker">Your data</div>
          <h1 className="ob-step-title">What your doctor will see</h1>
          <p className="ob-step-sub">Everything Owlet has been collecting — already in the round.</p>
        </div>

        {/* Permission list */}
        <div className="ob-perm-list" style={{ marginTop: 16 }}>
          {PERM_ROWS.map((row, i) => (
            <div
              key={row.key}
              className="ob-perm-row"
              onClick={() => togglePerm(row.key)}
              style={{ borderBottom: i < PERM_ROWS.length - 1 ? '1px solid rgba(212,212,249,0.05)' : 'none' }}
            >
              <div className="ob-perm-icon">{row.icon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="ob-perm-label">{row.label}</div>
                <div className="ob-perm-sublabel">{row.sub}</div>
              </div>
              <OBToggle on={!!prefs.permissions[row.key]} />
            </div>
          ))}
        </div>

        {/* Round detail */}
        <div style={{ marginTop: 22 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--foreground-muted)', marginBottom: 10 }}>
            Round detail
          </div>
          <div className="ob-segment">
            {ROUND_FORMATS.map(f => (
              <button
                key={f.id}
                className={`ob-segment-btn${prefs.format === f.id ? ' on' : ''}`}
                onClick={() => setPrefs(p => ({ ...p, format: f.id }))}
              >
                {f.label}
              </button>
            ))}
          </div>
          <p style={{ fontSize: 12, color: 'var(--foreground-muted)', marginTop: 8, lineHeight: '17px' }}>
            {selectedFormat.blurb}
          </p>
        </div>

        {/* Bottom note */}
        <div style={{ marginTop: 14, fontSize: 12, color: 'var(--foreground-muted)', padding: '10px 14px', background: 'rgba(212,212,249,0.04)', borderRadius: 10, border: '1px solid rgba(212,212,249,0.06)', lineHeight: '17px' }}>
          Rounds are most useful when they can see everything. Turn off anything you'd prefer to keep private.
        </div>
      </div>

      <OBFooterCTA>
        <button className="nw-cta" onClick={() => { window.haptics?.trigger('light'); onNext(); }}>
          Continue <RIcons.ChevronRight size={18} />
        </button>
      </OBFooterCTA>
    </div>
  );
}

// ─── OnboardStep3Screen ───────────────────────────────────
function OnboardStep3Screen({ onBack, onNext, prefs, setPrefs }) {
  const selected = AGENT_PERSONALITIES.find(p => p.id === prefs.agentPersonality) || AGENT_PERSONALITIES[0];

  return (
    <div className="ob-page ob-page--footer screen-enter">
      <OBStars count={8} />
      <div className="nw-aurora" />

      <div style={{ position: 'relative', zIndex: 1, padding: '16px 20px 0' }}>
        <OBTopBar onBack={onBack} step={3} totalSteps={3} />
        <OBProgress pct={100} />

        <div style={{ marginTop: 20 }}>
          <div className="ob-kicker">Your Care Agent</div>
          <h1 className="ob-step-title">How should your agent talk to you?</h1>
          <p className="ob-step-sub">Pick a voice. You can change this anytime from settings.</p>
        </div>

        {/* Personality grid */}
        <div className="ob-personality-grid" style={{ marginTop: 20 }}>
          {AGENT_PERSONALITIES.map(p => (
            <button
              key={p.id}
              className={`ob-personality-tile${prefs.agentPersonality === p.id ? ' on' : ''}`}
              onClick={() => { window.haptics?.trigger('selection'); setPrefs(prev => ({ ...prev, agentPersonality: p.id })); }}
            >
              <div className="ob-personality-tile-label">{p.label}</div>
              <div className="ob-personality-tile-blurb">{p.blurb}</div>
            </button>
          ))}
        </div>

        {/* Sample exchange — key forces re-entrance on personality change */}
        <div key={prefs.agentPersonality} className="ob-sample-exchange" style={{ marginTop: 16 }}>
          <div className="ob-sample-by">
            <RIcons.Sparkles size={10} />
            Care Agent · {selected.label}
          </div>
          <div className="ob-sample-q">"Should I be worried about the 4 AM stir?"</div>
          <div className="ob-sample-a">{selected.sampleResponse}</div>
        </div>
      </div>

      <OBFooterCTA>
        <button className="nw-cta glow" onClick={() => { window.haptics?.trigger('light'); onNext(); }}>
          See tonight's setup <RIcons.ChevronRight size={18} />
        </button>
        <div className="nw-cta-text" style={{ textAlign: 'center' }}>Your agent is always on your side.</div>
      </OBFooterCTA>
    </div>
  );
}

// ─── OnboardDoneScreen ────────────────────────────────────
function OnboardDoneScreen({ prefs, onDone }) {
  const [phase, setPhaseOB] = useStateOB(0);

  useEffectOB(() => {
    const timings = [1400, 1500, 1600, 2200];
    const timers = [];
    let acc = 0;
    timings.forEach((t, i) => {
      acc += t;
      timers.push(setTimeout(() => {
        if (i === timings.length - 1) {
          onDone();
        } else {
          setPhaseOB(i + 1);
        }
      }, acc));
    });
    return () => timers.forEach(clearTimeout);
  }, []); // eslint-disable-line

  const isFinal = phase >= 3;

  const phaseTitles = [
    "Reading Nora's 30 nights of history…",
    'Assigning your care team…',
    'Your Care Agent is ready…',
  ];
  const phaseSubs = [
    'Overnight vitals · sleep patterns · baseline',
    'A pediatric provider on call every night',
    'Signed reports, delivered by morning',
  ];

  return (
    <div className={`ob-page ob-ceremony${isFinal ? ' ob-ceremony--final' : ''}`}>
      <OBStars count={12} />

      <div className="ob-ceremony-copy">
        <span className="ob-ceremony-star" aria-hidden="true">✦</span>

        {!isFinal && (
          <>
            <div key={phase} className="ob-ceremony-kicker">Tonight</div>
            <div key={`t${phase}`} className="ob-ceremony-phase-title">{phaseTitles[phase]}</div>
            <div key={`s${phase}`} className="ob-ceremony-phase-sub">{phaseSubs[phase]}</div>
          </>
        )}

        {isFinal && (
          <>
            <div className="ob-ceremony-rule" />
            <h1 key="hl" className="ob-ceremony-headline">Morning Rounds</h1>
            <div className="ob-ceremony-rule" />
            <div className="ob-ceremony-badge">
              <span className="ob-ceremony-badge-dot" />
              Activated · First round at {prefs.morningTime}
            </div>
          </>
        )}
      </div>

      {!isFinal && (
        <div className="ob-ceremony-pips" aria-hidden="true">
          {[0, 1, 2, 3].map(i => (
            <span key={i} className={i <= phase ? 'on' : ''} />
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Export ───────────────────────────────────────────────
const ROnboarding = {
  OnboardHeroScreen,
  OnboardStep1Screen,
  OnboardStep2Screen,
  OnboardStep3Screen,
  OnboardDoneScreen,
};
