// AXIS-12 — System builder. Guided clarify → proposal → consent → build → done.
function BuilderScreen({ onClose, onBuilt }) {
  const [step, setStep] = React.useState('clarify');
  const [request, setRequest] = React.useState('');
  const [proposal, setProposal] = React.useState(null);
  const [pct, setPct] = React.useState(0);

  const SUGGESTIONS = [
    'Track sleep and morning energy together',
    'Log hot flashes against what I drank',
    'A wind-down routine before bed',
    'Understand what spikes my anxiety',
  ];

  const derive = (req) => {
    const s = req.toLowerCase();
    const map = [
      [/sleep.*energy|energy.*sleep/, 'Sleep & Energy Tracker', 'Logs your sleep hours and morning energy each day and charts them together, so you can see how last night shapes today.', 'experiment'],
      [/hot.?flash/, 'Hot Flash Tracker', 'Log each hot flash with its time and likely trigger, then see which triggers cluster with the worst nights.', 'experiment'],
      [/anx|stress|worr|mood/, 'Mood & Reflection', 'A quick daily check-in plus a short reflection, surfacing the days and patterns that spike.', 'journal'],
      [/routine|wind.?down|habit/, 'Wind-down Routine', 'A short evening checklist that nudges you to start winding down and logs whether you followed it.', 'routine'],
      [/sleep/, 'Sleep Tracker', 'Log bedtime, wake time, and how rested you feel, with a rolling 7-day view of your sleep window.', 'experiment'],
      [/step|walk|move|active|goal/, 'Movement Goal', 'A gentle daily step goal that adapts to your recent activity, with a streak to keep it going.', 'goal'],
    ];
    for (const [re, title, summary, face] of map) if (re.test(s)) return { title, summary, face };
    const words = req.replace(/[^\w\s]/g, '').split(/\s+/).filter(Boolean).slice(0, 5);
    const title = words.length ? words.map((w) => w[0].toUpperCase() + w.slice(1)).join(' ') : 'Custom Tracker';
    return { title, summary: 'A focused daily log for exactly what you described — log it and the trend builds over the coming week.', face: 'experiment' };
  };

  const toProposal = () => {
    const v = request.trim();
    if (!v) return;
    setProposal(derive(v)); setStep('proposal');
  };
  const build = () => {
    setStep('building'); setPct(6);
    const tick = setInterval(() => setPct((p) => {
      const n = Math.min(100, p + 9 + Math.random() * 13);
      if (n >= 100) {
        clearInterval(tick);
        setTimeout(() => { setStep('done'); if (onBuilt && proposal) onBuilt({ name: proposal.title, face: proposal.face || 'experiment' }); }, 350);
      }
      return n;
    }), 300);
  };

  const header = (title) => (
    <div style={{ padding: '4px 16px 12px', borderBottom: `1px solid ${M.rule}`, display: 'flex', alignItems: 'center', gap: 10 }}>
      <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 4, color: M.ink, marginLeft: -4, display: 'flex' }}>
        <window.MIcons.Close size={22} />
      </button>
      <div style={{ font: `500 16px/1.2 ${M.sans}`, color: M.ink }}>{title}</div>
    </div>
  );

  const ConsentRow = ({ title, body }) => (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '12px 0', borderTop: `1px solid ${M.ruleSoft}` }}>
      <window.MIcons.Check size={16} />
      <div><div style={{ font: `500 13.5px/1.3 ${M.sans}`, color: M.ink }}>{title}</div>
        <div style={{ font: `400 12.5px/1.45 ${M.sans}`, color: M.inkMuted, marginTop: 3 }}>{body}</div></div>
    </div>
  );

  return (
    <div style={{ background: M.canvas, minHeight: '100%' }}>
      {header('Build a system')}
      <div style={{ padding: '18px 16px 28px' }}>
        {step === 'clarify' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <DSCard variant="accent" padding={16}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <DSAxisAvatar size={20} radius={6} />
                <MEyebrow color={M.axisDark}>Axis · system builder</MEyebrow>
              </div>
              <div style={{ font: `400 15px/1.5 ${M.sans}`, color: M.ink }}>Describe what you want to track or change, and I'll turn it into a small block in your system.</div>
            </DSCard>
            <DSTextInput label="What do you want to build?" value={request} onChange={setRequest} isMultiline placeholder="e.g. I want to see how alcohol affects my sleep" autoFocus />
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {SUGGESTIONS.map((s) => <span key={s} onClick={() => setRequest(s)} style={{ cursor: 'pointer' }}><DSChip>{s}</DSChip></span>)}
            </div>
            <DSButton full onClick={toProposal}>Continue</DSButton>
          </div>
        )}

        {step === 'proposal' && proposal && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <MSectionTitle>Proposed module</MSectionTitle>
            <DSCard padding={18}>
              <div style={{ font: `500 18px/1.2 ${M.sans}`, color: M.ink, marginBottom: 8 }}>{proposal.title}</div>
              <div style={{ font: `400 14px/1.5 ${M.sans}`, color: M.inkSoft }}>{proposal.summary}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
                <DSChip variant="accent">AI-generated</DSChip><DSChip>Daily logging</DSChip><DSChip>7-day trend</DSChip>
              </div>
            </DSCard>
            <div style={{ font: `400 12.5px/1.4 ${M.sans}`, color: M.inkMuted, padding: '0 4px' }}>Based on: "{request}"</div>
            <DSButton full onClick={() => setStep('consent')}>Looks good — review & build</DSButton>
            <DSButton full variant="secondary" onClick={() => setStep('clarify')}>Adjust the request</DSButton>
          </div>
        )}

        {step === 'consent' && proposal && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <MSectionTitle>Before Axis builds this</MSectionTitle>
            <DSCard padding={16}>
              <ConsentRow title="What it does" body={`"${proposal.title}" runs in your prototype and stores what you log on this device.`} />
              <ConsentRow title="Your data" body="Entries stay local to your browser. Nothing is sent to a server in this prototype." />
              <ConsentRow title="You stay in control" body="Open, pause, or remove this module from your System tab any time." />
              <ConsentRow title="Not medical advice" body="Axis surfaces personal patterns, not clinical guidance." />
            </DSCard>
            <DSButton full onClick={build}>Build it</DSButton>
            <DSButton full variant="ghost" onClick={() => setStep('proposal')}>Back</DSButton>
          </div>
        )}

        {step === 'building' && proposal && (
          <div style={{ marginTop: 20 }}>
            <DSCard padding={18}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <DSAxisAvatar size={22} radius={7} />
                <div><div style={{ font: `500 15px/1.2 ${M.sans}`, color: M.ink }}>{proposal.title}</div>
                  <div style={{ font: `400 12.5px/1 ${M.sans}`, color: M.inkMuted, marginTop: 3 }}>{pct < 30 ? 'Queued…' : pct < 92 ? 'Building your module…' : 'Finishing up…'}</div></div>
              </div>
              <div style={{ height: 8, background: M.surfaceAlt, borderRadius: 999, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: Math.round(pct) + '%', background: M.axis, borderRadius: 999, transition: 'width .3s ease' }} />
              </div>
              <div style={{ textAlign: 'right', font: `400 11px/1 ${M.mono}`, color: M.inkFaint, marginTop: 6 }}>{Math.round(pct)}%</div>
            </DSCard>
          </div>
        )}

        {step === 'done' && proposal && (
          <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
            <DSCard variant="accent" padding={18}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <window.MIcons.Check size={22} />
                <div><div style={{ font: `500 16px/1.2 ${M.sans}`, color: M.ink }}>{proposal.title} is ready</div>
                  <div style={{ font: `400 13px/1.4 ${M.sans}`, color: M.inkSoft, marginTop: 3 }}>Added to your system.</div></div>
              </div>
            </DSCard>
            <DSButton full onClick={onClose}>Go to my system</DSButton>
            <DSButton full variant="ghost" onClick={() => { setStep('clarify'); setRequest(''); setProposal(null); }}>Build another</DSButton>
          </div>
        )}
      </div>
    </div>
  );
}
window.BuilderScreen = BuilderScreen;
