// Wind-down check-in modal + Wearable connect flow
const WindDownModal = ({ onClose }) => {
  const I = window.Icons;
  const toast = window.useToast();
  const [step, setStep] = useState(0);
  const [mood, setMood] = useState(null);
  const [stress, setStress] = useState(5);
  const [chosen, setChosen] = useState([]);

  const moods = [
    { v: 'great', icon: '😄', label: 'Great' },
    { v: 'good', icon: '🙂', label: 'Good' },
    { v: 'meh', icon: '😐', label: 'Meh' },
    { v: 'low', icon: '😔', label: 'Low' },
    { v: 'rough', icon: '😞', label: 'Rough' },
  ];
  const tasks = [
    { id: 't1', icon: '🧘', name: 'Box breathing', time: '5 min' },
    { id: 't2', icon: '☕', name: 'No caffeine after 2pm', time: 'Daily' },
    { id: 't3', icon: '📵', name: 'Screens off', time: '1h before bed' },
    { id: 't4', icon: '🛁', name: 'Warm shower', time: '90 min before' },
    { id: 't5', icon: '📖', name: 'Read fiction', time: '15 min' },
    { id: 't6', icon: '🌙', name: 'Body scan', time: '10 min' },
  ];

  const finish = () => { onClose(); toast.push(`Wind-down scheduled · ${chosen.length} tasks · +15 SLEEP tonight`); };

  return (
    <Modal onClose={onClose}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div className="row" style={{ gap: 10 }}>
          <Mascot score={70} size={42} hideZ/>
          <div>
            <div style={{ fontWeight: 600 }}>Tonight's Check-in</div>
            <div className="muted" style={{ fontSize: 12 }}>Step {step + 1} of 3 · with your Wellness Agent</div>
          </div>
        </div>
        <button className="icon-btn" onClick={onClose}><I.X size={14} /></button>
      </div>

      <div style={{ height: 4, background: 'var(--surface-2)', borderRadius: 999, marginBottom: 22 }}>
        <div style={{ width: `${(step + 1) / 3 * 100}%`, height: '100%', background: 'var(--primary)', borderRadius: 999, transition: 'width .3s' }}></div>
      </div>

      {step === 0 && (
        <div>
          <h3 className="serif" style={{ fontSize: 22, fontWeight: 400, margin: '0 0 6px' }}>How are you feeling?</h3>
          <div className="muted" style={{ fontSize: 13, marginBottom: 18 }}>One tap. Honest is best.</div>
          <div className="row" style={{ justifyContent: 'space-between', gap: 8 }}>
            {moods.map(m => (
              <button key={m.v} onClick={() => setMood(m.v)} style={{
                flex: 1, padding: '14px 6px', borderRadius: 12,
                background: mood === m.v ? 'var(--primary-soft)' : 'var(--surface-2)',
                border: '1.5px solid ' + (mood === m.v ? 'var(--primary)' : 'transparent'),
                display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center',
              }}>
                <span style={{ fontSize: 28 }}>{m.icon}</span>
                <span style={{ fontSize: 11, color: 'var(--text-2)' }}>{m.label}</span>
              </button>
            ))}
          </div>
          <div style={{ marginTop: 22 }}>
            <div className="row" style={{ justifyContent: 'space-between', fontSize: 13 }}>
              <span>Stress level</span>
              <span className="mono">{stress}/10</span>
            </div>
            <input type="range" min={0} max={10} value={stress} onChange={e => setStress(+e.target.value)} style={{ width: '100%', marginTop: 8, accentColor: 'var(--primary)' }} />
          </div>
          <button className="btn primary" style={{ width: '100%', marginTop: 22, justifyContent: 'center' }} disabled={!mood} onClick={() => setStep(1)}>Continue <I.ArrowRight size={13} /></button>
        </div>
      )}

      {step === 1 && (
        <div>
          <h3 className="serif" style={{ fontSize: 22, fontWeight: 400, margin: '0 0 6px' }}>Pick your wind-down tasks</h3>
          <div className="muted" style={{ fontSize: 13, marginBottom: 18 }}>I'll set reminders. Aim for 3.</div>
          <div className="grid grid-2" style={{ gap: 8 }}>
            {tasks.map(t => {
              const on = chosen.includes(t.id);
              return (
                <button key={t.id} onClick={() => setChosen(c => on ? c.filter(x => x !== t.id) : [...c, t.id])}
                  className="row" style={{
                    padding: 12, borderRadius: 12,
                    background: on ? 'var(--primary-soft)' : 'var(--surface-2)',
                    border: '1.5px solid ' + (on ? 'var(--primary)' : 'transparent'),
                    gap: 10, textAlign: 'left',
                  }}>
                  <span style={{ fontSize: 18 }}>{t.icon}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{t.name}</div>
                    <div className="muted" style={{ fontSize: 11 }}>{t.time}</div>
                  </div>
                  {on && <I.Check size={14} style={{ color: 'var(--primary)' }} />}
                </button>
              );
            })}
          </div>
          <div className="row" style={{ marginTop: 22, gap: 8 }}>
            <button className="btn ghost" onClick={() => setStep(0)}>Back</button>
            <button className="btn primary" style={{ flex: 1, justifyContent: 'center' }} disabled={chosen.length === 0} onClick={() => setStep(2)}>Continue · {chosen.length} chosen <I.ArrowRight size={13} /></button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div>
          <h3 className="serif" style={{ fontSize: 22, fontWeight: 400, margin: '0 0 6px' }}>Your wind-down is set ✦</h3>
          <div className="muted" style={{ fontSize: 13, marginBottom: 18 }}>Earn +15 SLEEP for completing all tasks tonight.</div>
          <div style={{ padding: 14, borderRadius: 12, background: 'linear-gradient(180deg, rgba(184,169,255,0.12), var(--surface-2))', border: '1px solid rgba(184,169,255,0.25)' }}>
            <div className="row" style={{ gap: 10, marginBottom: 10 }}>
              <I.Sparkle size={14} style={{ color: 'var(--primary)' }} />
              <div style={{ fontWeight: 600 }}>Wellness Agent says</div>
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--text-2)' }}>
              Mood {mood} + stress {stress}/10 — let's prioritise calm. I'll ping you at <b style={{ color: 'var(--text)' }}>9:30 PM</b> to start. Aim for lights out by <b style={{ color: 'var(--text)' }}>23:00</b> tonight.
            </div>
          </div>
          <button className="btn primary" style={{ width: '100%', marginTop: 22, justifyContent: 'center' }} onClick={finish}>Done <I.Check size={13} /></button>
        </div>
      )}
    </Modal>
  );
};

const ConnectWearableModal = ({ onClose, onConnect }) => {
  const I = window.Icons;
  const [connecting, setConnecting] = useState(null);
  const wearables = [
    { id: 'oura', name: 'Oura Ring', desc: 'Sleep, HRV, readiness, temperature', popular: true, img: (window.__resources && window.__resources.smartRing) || '/sleep/assets/smart-ring.png' },
    { id: 'apple', name: 'Apple Health', desc: 'iPhone + Apple Watch metrics' },
    { id: 'whoop', name: 'WHOOP', desc: 'Strain, recovery, sleep' },
    { id: 'garmin', name: 'Garmin', desc: 'Activity, sleep, stress' },
    { id: 'fitbit', name: 'Fitbit', desc: 'Steps, sleep, heart rate' },
    { id: 'manual', name: 'Manual entry', desc: "Log everything yourself — we'll guide you" },
  ];
  const handle = (id) => {
    setConnecting(id);
    setTimeout(() => { onConnect(id); }, 1400);
  };

  return (
    <Modal onClose={onClose} width={560}>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 14 }}>
        <div>
          <h3 className="serif" style={{ fontSize: 24, fontWeight: 400, margin: 0 }}>Connect a wearable</h3>
          <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>Sleepagotchi works best with continuous data.</div>
        </div>
        <button className="icon-btn" onClick={onClose}><I.X size={14} /></button>
      </div>

      <div className="col" style={{ gap: 8 }}>
        {wearables.map(w => (
          <button key={w.id} disabled={connecting} onClick={() => handle(w.id)}
            className="row" style={{
              padding: 14, borderRadius: 12,
              background: 'var(--surface-2)',
              border: '1px solid var(--border-soft)',
              gap: 12, textAlign: 'left', width: '100%',
              opacity: connecting && connecting !== w.id ? 0.5 : 1,
            }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: 'rgba(184,169,255,0.15)', display: 'grid', placeItems: 'center', color: 'var(--primary)', overflow: 'hidden' }}>
              {w.img ? <img src={w.img} alt={w.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/> : <I.Wave size={18} />}
            </div>
            <div style={{ flex: 1 }}>
              <div className="row" style={{ gap: 8 }}>
                <span style={{ fontWeight: 600 }}>{w.name}</span>
                {w.popular && <span className="tag violet">Popular</span>}
              </div>
              <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{w.desc}</div>
            </div>
            {connecting === w.id
              ? <span className="muted" style={{ fontSize: 12 }}>Connecting…</span>
              : <I.ChevronRight size={14} className="muted" />}
          </button>
        ))}
      </div>

      <div className="muted" style={{ fontSize: 11, textAlign: 'center', marginTop: 16 }}>Permissions can be revoked any time in Settings.</div>
    </Modal>
  );
};

const ConnectEmptyState = ({ onConnect }) => {
  const I = window.Icons;
  return (
    <div style={{ minHeight: '70vh', display: 'grid', placeItems: 'center', padding: 40 }}>
      <div style={{ maxWidth: 480, textAlign: 'center' }}>
        <div style={{ display: 'grid', placeItems: 'center', marginBottom: 20 }}>
          <Mascot score={50} size={150} />
        </div>
        <h2 className="serif" style={{ fontSize: 32, fontWeight: 400, margin: '0 0 10px' }}>Let's wake your dreamer up</h2>
        <p className="muted" style={{ fontSize: 14, lineHeight: 1.6 }}>
          Connect a wearable to unlock personalised insights, AI agents, and SLEEP rewards.
          Your data stays yours — encrypted and never sold.
        </p>
        <button className="btn primary" style={{ marginTop: 22, padding: '12px 22px' }} onClick={onConnect}>
          <I.Plus size={14} /> Connect a device
        </button>
        <div className="muted" style={{ fontSize: 12, marginTop: 14 }}>Oura · Apple Health · WHOOP · Garmin · Fitbit</div>
      </div>
    </div>
  );
};

Object.assign(window, { WindDownModal, ConnectWearableModal, ConnectEmptyState });
