// Add/edit subject modal. Used from sidebar and subject detail.

const EMOJI_SUGGESTIONS = ['📚', '📐', '📖', '🧬', '⚗️', '📜', '🌍', '🎨', '🎵', '💻', '🧮', '🧠', '⚖️', '🔬', '🌱'];

function SubjectDialog({ existing, onClose }) {
  const isEdit = !!existing;
  const [name, setName] = React.useState(existing?.name || '');
  const [emoji, setEmoji] = React.useState(existing?.emoji || '📚');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true); setErr(null);
    try {
      if (isEdit) await updateSubject(existing.id, { name, emoji });
      else await addSubject({ name, emoji });
      onClose();
    } catch (e2) {
      setErr(e2.message);
    } finally { setBusy(false); }
  };

  const remove = async () => {
    if (!confirm(`Delete "${existing.name}"? Guides linked to it will become orphaned but not deleted.`)) return;
    setBusy(true);
    try { await deleteSubject(existing.id); onClose({ deleted: true }); }
    catch (e) { setErr(e.message); setBusy(false); }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(20,22,43,0.4)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 200, padding: 20, backdropFilter: 'blur(4px)',
    }}>
      <form onClick={(e) => e.stopPropagation()} onSubmit={submit} style={{
        width: 360, background: 'white', borderRadius: 12,
        boxShadow: 'var(--shadow-l)', padding: 20,
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h2 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>{isEdit ? 'Edit subject' : 'New subject'}</h2>
          <button type="button" onClick={() => onClose()} style={{ border: 'none', background: 'transparent', fontSize: 18, cursor: 'pointer', color: 'var(--ink-mute)', padding: 0, lineHeight: 1 }}>×</button>
        </div>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-soft)' }}>Name</span>
          <input
            type="text" value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="e.g. AP Biology"
            required autoFocus
            style={{ height: 32, padding: '0 10px', border: '1px solid var(--line)', borderRadius: 6, fontSize: 12.5, fontFamily: 'inherit', outline: 'none' }}
          />
        </label>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-soft)' }}>Emoji</span>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {EMOJI_SUGGESTIONS.map((em) => (
              <button key={em} type="button" onClick={() => setEmoji(em)} style={{
                width: 32, height: 32, fontSize: 16, lineHeight: 1, padding: 0,
                border: `1.5px solid ${emoji === em ? 'var(--blue)' : 'var(--line)'}`,
                background: emoji === em ? 'var(--blue-wash)' : 'white',
                borderRadius: 6, cursor: 'pointer',
              }}>{em}</button>
            ))}
            <input
              type="text" value={emoji} onChange={(e) => setEmoji(e.target.value.slice(0, 4))}
              maxLength={4}
              style={{ width: 50, height: 32, padding: '0 8px', border: '1px solid var(--line)', borderRadius: 6, fontSize: 14, textAlign: 'center', fontFamily: 'inherit' }}
            />
          </div>
        </label>

        {err && (
          <div style={{ padding: '8px 10px', background: 'var(--coral-soft)', border: '1px solid var(--coral)', borderRadius: 6, fontSize: 11.5, color: '#8a3a20' }}>
            {err}
          </div>
        )}

        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          {isEdit && (
            <button type="button" className="btn ghost small" onClick={remove} disabled={busy} style={{ color: 'var(--coral)', borderColor: 'var(--coral)' }}>Delete</button>
          )}
          <div style={{ flex: 1 }} />
          <button type="button" className="btn ghost small" onClick={() => onClose()}>Cancel</button>
          <button type="submit" className="btn blue small" disabled={busy}>{busy ? 'Saving…' : (isEdit ? 'Save' : 'Create')}</button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { SubjectDialog });
