// settings.jsx — where Haven becomes yours: real plan data, edited in place
const { useState: uSS } = React;

const sInput = { width: '100%', padding: '10px 12px', fontSize: 14, fontFamily: 'var(--sans)', border: '1px solid var(--line-2)', borderRadius: 10, background: 'var(--surface)', color: 'var(--ink)', outline: 'none', boxSizing: 'border-box' };
const sLabel = { fontSize: 11.5, fontWeight: 700, color: 'var(--ink-3)', marginBottom: 5, display: 'block', textTransform: 'uppercase', letterSpacing: '.05em' };
const num = (v) => (v === '' || v == null ? 0 : (parseFloat(v) || 0));

// input with a focus buffer: you can type freely (incl. decimals);
// every keystroke still saves, display never fights your typing
function SField({ label, value, onChange, type = 'text', placeholder, prefix }) {
  const [local, setLocal] = uSS(null);
  const shown = local != null ? local : (value == null ? '' : value);
  return (
    <div style={{ minWidth: 0 }}>
      {label && <label style={sLabel}>{label}</label>}
      <div style={{ position: 'relative' }}>
        {prefix && <span style={{ position: 'absolute', left: 12, top: 10, color: 'var(--ink-3)', fontSize: 14 }}>{prefix}</span>}
        <input
          type={type} placeholder={placeholder} value={shown}
          onFocus={() => setLocal(String(value == null ? '' : value))}
          onChange={(e) => { setLocal(e.target.value); onChange(e.target.value); }}
          onBlur={() => setLocal(null)}
          style={{ ...sInput, paddingLeft: prefix ? 26 : 12 }}
        />
      </div>
    </div>
  );
}

function TrashBtn({ onClick, title = 'Remove' }) {
  const [h, setH] = uSS(false);
  return (
    <button onClick={onClick} title={title} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} style={{
      width: 38, height: 38, borderRadius: 10, border: '1px solid ' + (h ? 'var(--alert)' : 'var(--line-2)'),
      background: h ? 'var(--alert-soft)' : 'var(--surface)', color: h ? 'var(--alert)' : 'var(--ink-3)',
      display: 'grid', placeItems: 'center', transition: 'all .15s', flexShrink: 0,
    }}><Icons.trash size={17} /></button>
  );
}

function AddRowBtn({ onClick, children }) {
  return <Button size="sm" variant="ghost" icon={Icons.plus} onClick={onClick} style={{ marginTop: 4 }}>{children}</Button>;
}

function Settings() {
  const S = useHaven();
  const d = S.doc;
  const [confirming, setConfirming] = uSS(false);
  const [restorePreview, setRestorePreview] = uSS(null);   // { doc } or { error: true }

  const pickPlanDoc = async (e) => {
    const fl = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!fl) return;
    try { const r = await Store.uploadFile(fl); S.setPlanDoc({ name: r.name, url: r.url }); }
    catch (err) { alert("Couldn't store the file — is the NAS reachable?"); }
  };

  const pickBackup = (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!file) return;
    const r = new FileReader();
    r.onload = () => {
      try {
        const doc = JSON.parse(r.result);
        if (!doc || !doc.version || !doc.budget || !doc.child) throw new Error('not haven');
        setRestorePreview({ doc });
      } catch (err) { setRestorePreview({ error: true }); }
    };
    r.readAsText(file);
  };

  return (
    <div className="fade-in">
      <PageHead
        title="Settings"
        sub="This is where Haven becomes yours. Enter the details from the real NDIS plan and they flow through every screen — everything saves as you type."
      />

      {/* ── child & plan ── */}
      <SectionTitle sub="From the front page of the NDIS plan.">The plan</SectionTitle>
      <Card pad={20} style={{ marginBottom: 30 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          <SField label="Child's first name" value={d.child.name} onChange={(v) => S.setChild({ name: v })} />
          <SField label="NDIS number" value={d.child.ndis} onChange={(v) => S.setChild({ ndis: v })} />
          <SField label="Haven calls you" placeholder="e.g. Mum" value={d.child.parent} onChange={(v) => S.setChild({ parent: v })} />
          <SField label="Plan starts" type="date" value={d.planPeriod.start} onChange={(v) => v && S.setPlanPeriod({ start: v })} />
          <SField label="Plan ends" type="date" value={d.planPeriod.end} onChange={(v) => v && S.setPlanPeriod({ end: v })} />
        </div>
        <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          {d.planDoc && d.planDoc.url && (
            <a href={d.planDoc.url} target="_blank" rel="noopener" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 14, fontWeight: 600, color: 'var(--primary-ink)', textDecoration: 'none' }}><Icons.doc size={17} />Open the plan document</a>
          )}
          <label style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13.5, fontWeight: 600, color: 'var(--ink-2)', cursor: 'pointer', border: '1px solid var(--line-2)', borderRadius: 10, padding: '8px 13px' }}>
            <input type="file" accept=".pdf,.png,.jpg,.jpeg" style={{ display: 'none' }} onChange={pickPlanDoc} />
            <Icons.paperclip size={16} />{d.planDoc ? 'Replace the plan document…' : 'Attach the NDIS plan document…'}
          </label>
        </div>
        <div style={{ marginTop: 14 }}>
          <Note tone="info" icon="info">The plan dates drive the "on pace" marker, the days-remaining countdown and the review reminder — worth getting exactly right.</Note>
        </div>
      </Card>

      {/* ── budget ── */}
      <SectionTitle sub={<>The amounts from the plan, per support area. "Spent so far" is for money already used before you started Haven — it keeps your remaining figures honest.</>}>Budget</SectionTitle>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 30 }}>
        {d.budget.map((c) => (
          <Card key={c.key} pad={20}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontWeight: 700, fontSize: 16, whiteSpace: 'nowrap' }}>
                <span style={{ width: 10, height: 10, borderRadius: 3, background: c.color, flexShrink: 0 }} />{c.name}
              </span>
              <span style={{ fontSize: 14, color: 'var(--ink-2)', fontVariantNumeric: 'tabular-nums' }}>{fmtMoney(c.budget)} total</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 150px 150px 38px', gap: 10, marginBottom: 7 }}>
              <span style={sLabel}>Support area</span><span style={sLabel}>Yearly budget</span><span style={sLabel}>Spent so far</span><span></span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {c.subs.map((s, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 150px 150px 38px', gap: 10, alignItems: 'center' }}>
                  <SField value={s.name} placeholder="e.g. Improved Daily Living" onChange={(v) => S.subPatch(c.key, i, { name: v })} />
                  <SField type="number" prefix="$" value={s.budget === 0 ? '' : s.budget} placeholder="0" onChange={(v) => S.subPatch(c.key, i, { budget: num(v) })} />
                  <SField type="number" prefix="$" value={s.spent === 0 ? '' : s.spent} placeholder="0" onChange={(v) => S.subPatch(c.key, i, { spent: num(v) })} />
                  <TrashBtn onClick={() => S.subRemove(c.key, i)} />
                </div>
              ))}
            </div>
            <AddRowBtn onClick={() => S.subAdd(c.key)}>Add a support area</AddRowBtn>
          </Card>
        ))}
      </div>

      {/* ── providers ── */}
      <SectionTitle sub="Everyone you buy supports from. These appear in the claim form's provider list." action={<Button size="sm" icon={Icons.plus} onClick={() => S.listAdd('providers', { name: '', short: '', cat: 'core', sub: '', rate: '', agreementEnds: null })}>Add provider</Button>}>Providers</SectionTitle>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 30 }}>
        {d.providers.length === 0 && <Note tone="info" icon="info">No providers yet — add your therapists, programs and suppliers so logging a claim is one click.</Note>}
        {d.providers.map((p) => (
          <Card key={p.id} pad={18}>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.3fr 38px', gap: 10, alignItems: 'end', marginBottom: 10 }}>
              <SField label="Provider name" placeholder="e.g. Bright Steps Occupational Therapy" value={p.name}
                onChange={(v) => S.listPatch('providers', p.id, { name: v, short: v.split(' ').slice(0, 3).join(' ') })} />
              <div>
                <label style={sLabel}>Budget category</label>
                <select style={sInput} value={p.cat} onChange={(e) => S.listPatch('providers', p.id, { cat: e.target.value })}>
                  {d.budget.map((b) => <option key={b.key} value={b.key}>{b.name}</option>)}
                </select>
              </div>
              <TrashBtn onClick={() => S.listRemove('providers', p.id)} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 10 }}>
              <SField label="Support area" placeholder="e.g. Improved Daily Living (therapies)" value={p.sub} onChange={(v) => S.listPatch('providers', p.id, { sub: v })} />
              <SField label="Rate" placeholder="$193.99 / hr" value={p.rate} onChange={(v) => S.listPatch('providers', p.id, { rate: v })} />
              <SField label="Agreement ends" type="date" value={p.agreementEnds || ''} onChange={(v) => S.listPatch('providers', p.id, { agreementEnds: v || null })} />
            </div>
          </Card>
        ))}
      </div>

      {/* ── workers ── */}
      <SectionTitle sub="People you employ and pay directly." action={<Button size="sm" icon={Icons.plus} onClick={() => S.listAdd('workers', { name: '', role: 'Support Worker', rate: 0, initials: '', cat: 'core' })}>Add worker</Button>}>Support workers</SectionTitle>
      <Card pad={20} style={{ marginBottom: 30 }}>
        {d.workers.length === 0 && <div style={{ color: 'var(--ink-3)', fontSize: 14, textAlign: 'center', padding: 10 }}>No support workers yet.</div>}
        {d.workers.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 150px 38px', gap: 10, marginBottom: 7 }}>
            <span style={sLabel}>Name</span><span style={sLabel}>Role</span><span style={sLabel}>Hourly rate</span><span></span>
          </div>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {d.workers.map((w) => (
            <div key={w.id} style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 150px 38px', gap: 10, alignItems: 'center' }}>
              <SField value={w.name} placeholder="Full name" onChange={(v) => S.listPatch('workers', w.id, { name: v, initials: v.split(' ').map((x) => x[0] || '').join('').slice(0, 2).toUpperCase() })} />
              <SField value={w.role} onChange={(v) => S.listPatch('workers', w.id, { role: v })} />
              <SField type="number" prefix="$" value={w.rate === 0 ? '' : w.rate} placeholder="0.00" onChange={(v) => S.listPatch('workers', w.id, { rate: num(v) })} />
              <TrashBtn onClick={() => S.listRemove('workers', w.id)} />
            </div>
          ))}
        </div>
      </Card>

      {/* ── goals ── */}
      <SectionTitle sub="The goals written in the plan — progress feeds your review prep." action={<Button size="sm" icon={Icons.plus} onClick={() => S.listAdd('goals', { text: '', supports: '', progress: 0, note: '' })}>Add goal</Button>}>Goals</SectionTitle>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 34 }}>
        {d.goals.length === 0 && <Note tone="info" icon="goal">No goals yet — copy them in from the plan document.</Note>}
        {d.goals.map((g) => (
          <Card key={g.id} pad={18}>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 130px 38px', gap: 10, alignItems: 'end', marginBottom: 10 }}>
              <SField label="Goal" placeholder="e.g. Communicate needs more independently" value={g.text} onChange={(v) => S.listPatch('goals', g.id, { text: v })} />
              <SField label="Progress %" type="number" value={Math.round(g.progress * 100) === 0 ? '' : Math.round(g.progress * 100)} placeholder="0"
                onChange={(v) => S.listPatch('goals', g.id, { progress: Math.min(100, Math.max(0, num(v))) / 100 })} />
              <TrashBtn onClick={() => S.listRemove('goals', g.id)} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <SField label="Supported by" placeholder="e.g. Speech pathology, AAC device" value={g.supports} onChange={(v) => S.listPatch('goals', g.id, { supports: v })} />
              <SField label="Progress note" placeholder="How it's going, in your words" value={g.note} onChange={(v) => S.listPatch('goals', g.id, { note: v })} />
            </div>
          </Card>
        ))}
      </div>

      {/* ── backup & restore ── */}
      <SectionTitle sub="Your NAS keeps automatic daily snapshots, but a backup you hold yourself is good sense — keep one on a USB stick or in your email.">Backup & restore</SectionTitle>
      <Card pad={20} style={{ marginBottom: 30 }}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <Button icon={Icons.download} variant="white" onClick={() => S.downloadBackup()}>Download backup file</Button>
          <label style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '11px 18px', fontSize: 15, fontWeight: 600, fontFamily: 'var(--sans)', color: 'var(--ink-2)', background: 'transparent', border: '1px solid var(--line-2)', borderRadius: 12, cursor: 'pointer', lineHeight: 1.1 }}>
            <input type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={pickBackup} />
            <Icons.upload size={18} /> Restore from a backup…
          </label>
        </div>
        <div style={{ marginTop: 14 }}>
          <Note tone="info" icon="info">The backup file holds <b>every record</b> — budgets, claims, invoices, workers, goals and notes. Your uploaded invoice <b>files</b> live separately in <b>web/haven/api/files</b> on the NAS; include that folder in your Hyper Backup.</Note>
        </div>
      </Card>

      {/* ── start fresh ── */}
      <SectionTitle sub="For when you're ready to swap the sample records for real life.">Start fresh</SectionTitle>
      <Card pad={20} style={{ borderColor: '#e8c4ba', marginBottom: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between', flexWrap: 'wrap' }}>
          <div style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55, maxWidth: 560 }}>
            Clears every sample claim, invoice, timesheet, provider, worker and goal, and zeroes the budgets — leaving a clean Haven ready for the real plan. {d.child.name ? `${d.child.name}'s` : 'The'} name and plan dates stay.
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <Button variant="ghost" icon={Icons.sparkles} onClick={() => S.loadSample()}>Load sample data</Button>
            <Button variant="white" icon={Icons.alert} onClick={() => setConfirming(true)} style={{ color: 'var(--alert)', borderColor: '#e8c4ba' }}>Start fresh…</Button>
          </div>
        </div>
      </Card>

      <Modal open={confirming} onClose={() => setConfirming(false)} width={480} title="Start fresh?" sub="A clean slate for real records.">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Note tone="amber" icon="alert">This removes <b>all</b> records currently in Haven on every computer. Your NAS keeps a daily snapshot in <b>api/store/backups</b>, so yesterday's data is still recoverable if you change your mind.</Note>
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
            <Button variant="ghost" onClick={() => setConfirming(false)}>Keep everything</Button>
            <Button onClick={() => { S.startFresh(); setConfirming(false); window.scrollTo(0, 0); }} style={{ background: 'var(--alert)', borderColor: 'var(--alert)' }} icon={Icons.check}>Yes, start fresh</Button>
          </div>
        </div>
      </Modal>

      {/* ── restore preview ── */}
      <Modal open={!!restorePreview} onClose={() => setRestorePreview(null)} width={480}
        title={restorePreview && restorePreview.error ? "That's not a Haven backup" : 'Restore this backup?'}
        sub={restorePreview && restorePreview.error ? null : 'Check it\u2019s the right one before anything changes.'}>
        {restorePreview && restorePreview.error ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Note tone="amber" icon="alert">That file couldn't be read as a Haven backup. Look for a file named like <b>haven-backup-2026-06-10.json</b>.</Note>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}><Button variant="ghost" onClick={() => setRestorePreview(null)}>Close</Button></div>
          </div>
        ) : restorePreview && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Card pad={16} style={{ background: 'var(--surface-2)', border: 'none' }}>
              {[
                ['For', `${restorePreview.doc.child.name || '—'} · NDIS ${restorePreview.doc.child.ndis || '—'}`],
                ['Last saved', restorePreview.doc.updatedAt ? new Date(restorePreview.doc.updatedAt).toLocaleString('en-AU') : '—'],
                ['Claims', (restorePreview.doc.claims || []).length],
                ['Invoices', (restorePreview.doc.invoices || []).length],
                ['Providers · workers · goals', `${(restorePreview.doc.providers || []).length} · ${(restorePreview.doc.workers || []).length} · ${(restorePreview.doc.goals || []).length}`],
              ].map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 14, padding: '7px 0', fontSize: 14, borderBottom: '1px solid var(--line)' }}>
                  <span style={{ color: 'var(--ink-2)' }}>{k}</span><span style={{ fontWeight: 600, textAlign: 'right' }}>{v}</span>
                </div>
              ))}
            </Card>
            <Note tone="amber" icon="alert">Restoring replaces <b>everything currently in Haven</b>, on every computer. Consider downloading a backup of the current data first.</Note>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
              <Button variant="ghost" onClick={() => setRestorePreview(null)}>Cancel</Button>
              <Button icon={Icons.check} onClick={() => { S.restore(restorePreview.doc); setRestorePreview(null); window.scrollTo(0, 0); }}>Restore this backup</Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

Object.assign(window, { Settings });
