// Settings — license, paired devices, backup, contributors, danger zone.
// Opens as an overlay from the dashboard top-right gear.

function SettingsScreen({ onBack, onPairDevice }) {
  const wedding = useWedding();
  const { resetDemo, startFresh } = useStore();
  const [confirming, setConfirming] = React.useState(null); // null | 'demo' | 'fresh'
  const [revealed, setRevealed] = React.useState(false);
  const [editingBasics, setEditingBasics] = React.useState(false);
  const [pairOpen, setPairOpen] = React.useState(false);

  const basicsFields = () => [
    { name: 'brides',     label: 'Your name',    type: 'text', placeholder: 'e.g. Alex Morgan' },
    { name: 'groom',      label: 'Their name',   type: 'text', placeholder: 'e.g. Jordan Reed' },
    { name: 'dateISO',    label: 'Wedding date', type: 'date',
      hint: 'Format: 2026-10-04' },
    { name: 'venue',      label: 'Venue',        type: 'text', placeholder: 'e.g. Hollow Tree' },
    { name: 'city',       label: 'City',         type: 'text', placeholder: 'e.g. Hudson Valley, NY' },
    { name: 'timeLabel',  label: 'Ceremony time', type: 'text', placeholder: 'e.g. 4:00 PM' },
    { name: 'guestCount', label: 'Guest count',  type: 'number', min: 0, max: 1000, step: 1, default: 0, unit: 'guests' },
    { name: 'budget',     label: 'Target budget', type: 'number', min: 0, max: 1000000, step: 500, default: 0, unit: '$' },
  ];

  const submitBasics = (v) => {
    let iso = v.dateISO || '';
    // Accept "2026-10-04" form, normalize to full ISO.
    if (iso && !iso.includes('T')) {
      const d = new Date(iso + 'T16:00:00');
      iso = isNaN(d.getTime()) ? '' : d.toISOString();
    }
    wedding.setWedding({
      brides: (v.brides || '').trim(),
      groom:  (v.groom  || '').trim(),
      dateISO: iso,
      venue:  (v.venue || '').trim(),
      city:   (v.city  || '').trim(),
      cityShort: (v.city || '').trim(),
      timeLabel: (v.timeLabel || '').trim(),
      guestCount: Number(v.guestCount) || 0,
      budget:     Number(v.budget)     || 0,
    });
    setEditingBasics(false);
  };

  const initialBasics = {
    brides:     wedding.brides     || '',
    groom:      wedding.groom      || '',
    dateISO:    wedding.dateISO ? wedding.dateISO.slice(0, 10) : '',
    venue:      wedding.venue      || '',
    city:       wedding.city       || '',
    timeLabel:  wedding.timeLabel  || '',
    guestCount: wedding.guestCount || 0,
    budget:     wedding.budget     || 0,
  };

  const exportBackup = () => {
    try {
      const raw = localStorage.getItem('weddingos.v1') || '{}';
      const blob = new Blob([raw], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `weddingos-${new Date().toISOString().slice(0,10)}.json`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (e) {}
  };

  return (
    <div style={{ background: W.bg, paddingBottom: 28, minHeight: 874 }}>
      <div style={{ paddingTop: 56 }}/>

      {/* Back row */}
      <div style={{
        padding: '4px 22px 12px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          background: W.card, border: `0.5px solid ${W.line}`,
          width: 36, height: 36, borderRadius: 999, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 0,
        }}>
          <Icon name="chevronL" size={14} color={W.ink2}/>
        </button>
        <div style={{
          fontFamily: FONT_UI, fontSize: 11, fontWeight: 600,
          letterSpacing: 1.6, textTransform: 'uppercase', color: W.muted,
        }}>Settings</div>
        <div style={{ width: 36 }}/>
      </div>

      {/* Hero — your wedding */}
      <div style={{ padding: '12px 22px 22px' }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
          letterSpacing: 2, textTransform: 'uppercase', color: W.muted,
        }}>Your wedding</div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 32, fontWeight: 500,
          color: W.ink, letterSpacing: -0.3, lineHeight: 1.1, marginTop: 6,
        }}>
          {wedding.brides} <span style={{ fontStyle: 'italic' }}>&amp;</span> {wedding.groom}
        </div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 14.5,
          color: W.ink2, marginTop: 6,
        }}>{wedding.dateLabel} · {wedding.city}</div>
      </div>

      <SettingsGroup label="Wedding details">
        <SettingsRow icon="rings"    label="Couple"        value={wedding.couple || <em style={{ color: W.muted }}>Not set</em>}
          onClick={() => setEditingBasics(true)} chevron/>
        <SettingsRow icon="calendar" label="Wedding date"  value={wedding.dateLabel || <em style={{ color: W.muted }}>Not set</em>}
          onClick={() => setEditingBasics(true)} chevron/>
        <SettingsRow icon="leaf"     label="Venue"         value={wedding.venue || <em style={{ color: W.muted }}>Not set</em>}
          onClick={() => setEditingBasics(true)} chevron/>
        <SettingsRow icon="home"     label="City"          value={wedding.city || <em style={{ color: W.muted }}>Not set</em>}
          onClick={() => setEditingBasics(true)} chevron/>
        <SettingsRow icon="users"    label="Guest count"   value={wedding.guestCount ? `≈ ${wedding.guestCount}` : <em style={{ color: W.muted }}>Not set</em>}
          onClick={() => setEditingBasics(true)} chevron/>
        <SettingsRow icon="wallet"   label="Budget"        value={wedding.budget ? fmt$(wedding.budget) : <em style={{ color: W.muted }}>Not set</em>}
          onClick={() => setEditingBasics(true)} chevron/>
      </SettingsGroup>

      <SettingsGroup label="Sync & license">
        <SettingsRow icon="sparkle" label="Status" value={
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: W.green }}/>
            <span style={{ color: W.green, fontFamily: FONT_UI, fontSize: 12, fontWeight: 600,
              letterSpacing: 1, textTransform: 'uppercase' }}>Synced</span>
          </span>
        }/>
        <SettingsRow icon="check" label="Access code"
          onClick={() => setRevealed(r => !r)}
          value={(() => {
            const lic = (typeof localStorage !== 'undefined' && localStorage.getItem('weddingos.license')) || '';
            const masked = lic
              ? lic.split('-').map((s, i) => i < 2 ? s : '····').join('–')
              : 'Not activated';
            const full = lic ? lic.replace(/-/g, '–') : 'Not activated';
            return (
              <span style={{
                fontFamily: FONT_MONO, fontSize: 11.5, color: W.ink2, letterSpacing: 1.2,
              }}>{revealed ? full : masked}</span>
            );
          })()}
          chevron
        />
        <SettingsRow icon="users" label="Paired devices" value="1 of 5"
          onClick={() => setPairOpen(true)} chevron/>
        <SettingsRow icon="plus" label="Pair another device"
          onClick={() => setPairOpen(true)}
          value={<span style={{ color: W.clay, fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500 }}>Get code</span>}/>
      </SettingsGroup>

      <SettingsGroup label="Contributors">
        {BUDGET.contributors.map((c) => (
          <SettingsRow key={c.name} icon="wallet" label={c.name} value={fmt$(c.amount)}/>
        ))}
      </SettingsGroup>

      <SettingsGroup label="Backup">
        <SettingsRow icon="arrow" label="Export backup as JSON"
          onClick={exportBackup}
          value={<span style={{ color: W.clay, fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500 }}>Download</span>}/>
        <SettingsRow icon="check" label="Import from backup"
          value={<span style={{ color: W.faint, fontFamily: FONT_UI, fontSize: 12.5 }}>Choose file</span>}/>
        <SettingsRow icon="sparkle" label="Print pack"
          onClick={() => printAllReports()}
          value={<span style={{ color: W.clay, fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500 }}>Print</span>}/>
      </SettingsGroup>

      <SettingsGroup label="About">
        <SettingsRow icon="heart"   label="Version"   value="1.0.0"/>
        <SettingsRow icon="sparkle" label="Storage"   value="Local + Cloudflare"/>
        <SettingsRow icon="leaf"    label="Region"    value="US-West"/>
      </SettingsGroup>

      {/* Danger zone */}
      <div style={{ padding: '0 22px 32px' }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
          letterSpacing: 1.8, textTransform: 'uppercase', color: W.red,
          marginBottom: 8, paddingLeft: 4,
        }}>Danger zone</div>
        {!confirming ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <button onClick={() => setConfirming('fresh')} style={{
              width: '100%', padding: '14px 16px',
              background: W.card, color: W.ink,
              border: `0.5px solid ${W.line}`, borderRadius: 14,
              cursor: 'pointer', textAlign: 'left',
              fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500,
            }}>
              Start fresh
              <div style={{ fontSize: 11.5, color: W.muted, marginTop: 4, fontWeight: 400 }}>
                Wipes everything. You start with empty guest list, budget, vendors, tables.
              </div>
            </button>
            <button onClick={() => setConfirming('demo')} style={{
              width: '100%', padding: '14px 16px',
              background: W.card, color: W.ink2,
              border: `0.5px solid ${W.line}`, borderRadius: 14,
              cursor: 'pointer', textAlign: 'left',
              fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500,
            }}>
              Reset to demo wedding
              <div style={{ fontSize: 11.5, color: W.muted, marginTop: 4, fontWeight: 400 }}>
                Loads the example wedding so you can see how it's meant to look.
              </div>
            </button>
          </div>
        ) : (
          <div style={{
            padding: 16, background: '#f4e0d8', borderRadius: 14,
            border: `0.5px solid ${W.red}`,
          }}>
            <div style={{
              fontFamily: FONT_UI, fontSize: 13, color: '#7d3a2d', fontWeight: 500,
              marginBottom: 12,
            }}>
              {confirming === 'fresh'
                ? 'This will erase all your planning data. Continue?'
                : 'This will replace everything with the example wedding. Continue?'}
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setConfirming(null)} style={{
                flex: 1, padding: '11px 0', background: 'transparent',
                color: '#7d3a2d', border: `0.5px solid ${W.red}`,
                borderRadius: 999, cursor: 'pointer',
                fontFamily: FONT_UI, fontSize: 13, fontWeight: 500,
              }}>Cancel</button>
              <button onClick={() => {
                if (confirming === 'fresh') startFresh();
                else resetDemo();
                setConfirming(null);
              }} style={{
                flex: 1, padding: '11px 0', background: W.red, color: '#fff',
                border: 'none', borderRadius: 999, cursor: 'pointer',
                fontFamily: FONT_UI, fontSize: 13, fontWeight: 500,
              }}>
                {confirming === 'fresh' ? 'Start fresh' : 'Reset'}
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Footer */}
      <div style={{
        padding: '0 22px 30px', textAlign: 'center',
        fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 12.5,
        color: W.muted, lineHeight: 1.6,
      }}>
        WeddingOS · made with care · no accounts, no tracking
      </div>

      {editingBasics && (
        <FormSheet
          title="Wedding details"
          eyebrow="Edit"
          fields={basicsFields()}
          initial={initialBasics}
          submitLabel="Save"
          onClose={() => setEditingBasics(false)}
          onSubmit={submitBasics}
        />
      )}

      {pairOpen && <PairDeviceSheet onClose={() => setPairOpen(false)}/>}
    </div>
  );
}

// Simulated 6-digit pair flow — for the actual round-trip we have the Cloudflare
// Worker spec in /worker; the in-app side is a single-use code with a countdown.
function PairDeviceSheet({ onClose }) {
  const codeRef = React.useRef(null);
  if (!codeRef.current) {
    codeRef.current = Math.floor(100000 + Math.random() * 900000).toString();
  }
  const code = codeRef.current;
  const [remaining, setRemaining] = React.useState(600); // 10 minutes
  const [copied, setCopied] = React.useState(false);

  React.useEffect(() => {
    const id = setInterval(() => setRemaining(s => Math.max(0, s - 1)), 1000);
    return () => clearInterval(id);
  }, []);

  const mm = String(Math.floor(remaining / 60)).padStart(2, '0');
  const ss = String(remaining % 60).padStart(2, '0');

  const copyCode = () => {
    try {
      if (navigator.clipboard) navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 1400);
    } catch {}
  };

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0,
        background: 'rgba(29,24,18,0.36)',
        backdropFilter: 'blur(2px)',
        zIndex: 80,
        animation: 'wos-fade-in 200ms ease',
      }}/>
      <div style={{
        position: 'fixed', bottom: 0, left: 0, right: 0,
        background: W.card,
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        boxShadow: '0 -16px 44px -20px rgba(29,24,18,0.4)',
        padding: '14px 0 26px',
        zIndex: 90, maxHeight: '92dvh',
        maxWidth: 640, margin: '0 auto',
        display: 'flex', flexDirection: 'column',
        animation: 'wos-sheet-rise 280ms cubic-bezier(0.2, 0.8, 0.2, 1)',
      }}>
        <div style={{
          width: 38, height: 4, borderRadius: 999, background: W.faint,
          margin: '0 auto 12px',
        }}/>

        <div style={{
          padding: '0 22px 14px',
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
          borderBottom: `0.5px solid ${W.lineSoft}`,
        }}>
          <div>
            <div style={{
              fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
              letterSpacing: 1.8, textTransform: 'uppercase', color: W.muted,
            }}>Pair a device</div>
            <div style={{
              fontFamily: FONT_DISPLAY, fontSize: 22, fontWeight: 500,
              color: W.ink, letterSpacing: -0.2, lineHeight: 1.1, marginTop: 4,
            }}>Enter this code on the other device</div>
          </div>
          <button onClick={onClose} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontFamily: FONT_UI, fontSize: 13, color: W.muted, padding: 0,
          }}>Done</button>
        </div>

        <div style={{ padding: '28px 22px 8px', flex: 1, overflowY: 'auto' }}>
          {/* Big 6-digit code */}
          <div style={{
            display: 'flex', justifyContent: 'center', gap: 8,
          }}>
            {code.split('').map((d, i) => (
              <div key={i} style={{
                width: 42, height: 56, borderRadius: 10,
                background: W.bg, border: `0.5px solid ${W.line}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: FONT_DISPLAY, fontSize: 32, fontWeight: 500, color: W.ink,
                boxShadow: '0 1px 2px rgba(60,40,20,0.03), 0 8px 18px -10px rgba(60,40,20,0.1)',
              }}>{d}</div>
            ))}
          </div>

          {/* Countdown + copy */}
          <div style={{
            marginTop: 18, textAlign: 'center',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14,
          }}>
            <div style={{
              fontFamily: FONT_UI, fontSize: 12, color: W.muted, letterSpacing: 0.3,
            }}>
              Expires in <span style={{
                fontFamily: FONT_MONO, color: remaining < 60 ? W.red : W.clay, fontWeight: 500,
              }}>{mm}:{ss}</span>
            </div>
            <button onClick={copyCode} style={{
              padding: '6px 12px', background: W.cardSoft, color: W.ink2,
              border: `0.5px solid ${W.line}`, borderRadius: 999, cursor: 'pointer',
              fontFamily: FONT_UI, fontSize: 11.5, fontWeight: 500,
            }}>{copied ? 'Copied' : 'Copy code'}</button>
          </div>

          {/* Steps */}
          <div style={{
            marginTop: 26, padding: '18px 16px',
            background: W.cardSoft, borderRadius: 14,
            border: `0.5px solid ${W.lineSoft}`,
          }}>
            <PairStep n={1} text={<>Open <strong>WeddingOS</strong> on your other device.</>}/>
            <PairStep n={2} text={<>Tap <strong>Already have a wedding?</strong> on the welcome screen.</>}/>
            <PairStep n={3} text={<>Enter the code above. Your planning syncs automatically.</>}/>
          </div>

          <div style={{
            marginTop: 18, textAlign: 'center',
            fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 12.5,
            color: W.muted, lineHeight: 1.5,
          }}>
            Single-use. The code expires in 10 minutes — generate a fresh one any time.
          </div>
        </div>
      </div>
    </>
  );
}

function PairStep({ n, text }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start', gap: 12,
      marginBottom: n < 3 ? 12 : 0,
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 999, background: W.ink, color: W.bg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: FONT_UI, fontSize: 11, fontWeight: 600, flexShrink: 0,
      }}>{n}</div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 13, color: W.ink, lineHeight: 1.5, paddingTop: 2,
      }}>{text}</div>
    </div>
  );
}

function SettingsGroup({ label, children }) {
  return (
    <div style={{ padding: '0 16px 22px' }}>
      <div style={{
        fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
        letterSpacing: 1.8, textTransform: 'uppercase', color: W.muted,
        marginBottom: 8, paddingLeft: 6,
      }}>{label}</div>
      <Card style={{ padding: 0, overflow: 'hidden' }}>
        {React.Children.toArray(children).map((child, i, arr) => (
          <React.Fragment key={i}>
            {child}
            {i < arr.length - 1 && (
              <div style={{ height: 0.5, background: W.lineSoft, marginLeft: 50 }}/>
            )}
          </React.Fragment>
        ))}
      </Card>
    </div>
  );
}

function SettingsRow({ icon, label, value, onClick, chevron }) {
  return (
    <div onClick={onClick} style={{
      padding: '12px 14px',
      display: 'flex', alignItems: 'center', gap: 12,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8, background: W.cardSoft,
        border: `0.5px solid ${W.lineSoft}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Icon name={icon} size={13} color={W.clayDeep} strokeWidth={1.4}/>
      </div>
      <div style={{
        flex: 1, fontFamily: FONT_UI, fontSize: 13.5, color: W.ink,
      }}>{label}</div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 13, color: W.ink2,
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        {value}
        {chevron && <Icon name="chevron" size={11} color={W.faint}/>}
      </div>
    </div>
  );
}

Object.assign(window, { SettingsScreen });
