// NewQuizModal — clean rewrite. Tabbed scope picker (one input visible at a time)
// for tighter layout. Last-edited wins via tab selection.

const { useState: useNQState } = React;

function NewQuizModal({ chapter, onCancel, onCreate }) {
  const t = window.LexTokens;
  const [count, setCount]         = useNQState(10);
  const [style, setStyle]         = useNQState('fact');
  const [scopeKind, setScopeKind] = useNQState('whole');
  const [pageFrom, setPageFrom]   = useNQState(chapter.pageStart);
  const [pageTo,   setPageTo]     = useNQState(chapter.pageEnd);
  const [topic,    setTopic]      = useNQState('');
  const [caseId,   setCaseId]     = useNQState(chapter.cases?.[0]?.id || '');

  const cases = chapter.cases || [];

  function buildScope() {
    if (scopeKind === 'pages') return { kind:'pages', from: pageFrom, to: pageTo };
    if (scopeKind === 'topic') return { kind:'topic', topic: topic.trim() || 'whole chapter' };
    if (scopeKind === 'case')  return { kind:'case',  caseId };
    return null;
  }

  function submit() {
    onCreate({
      count: Math.max(1, Math.min(100, Number(count) || 10)),
      style,
      scope: buildScope(),
    });
  }

  const scopeTabs = [
    { v: 'whole', label: 'Whole chapter' },
    { v: 'pages', label: 'Pages' },
    { v: 'topic', label: 'Topic' },
    { v: 'case',  label: 'Case', disabled: cases.length === 0 },
  ];

  return (
    <Modal onClose={onCancel} title="New quiz" subtitle={chapter.displayName}>
      <div style={nqS.body}>

        {/* Number of questions */}
        <Section label="Number of questions">
          <Counter value={count} onChange={setCount} min={1} max={100} />
        </Section>

        {/* Question style */}
        <Section label="Question style">
          <div style={nqS.styleGrid}>
            {[
              { v: 'fact',        title: 'Fact-based',  desc: 'Rules, holdings, definitions' },
              { v: 'application', title: 'Application', desc: 'Hypotheticals & bar-style scenarios' },
              { v: 'mixed',       title: 'Mixed',       desc: 'Half fact-based, half application' },
            ].map(opt => {
              const on = style === opt.v;
              return (
                <button
                  key={opt.v}
                  onClick={() => setStyle(opt.v)}
                  style={{
                    textAlign: 'left',
                    padding: '14px 16px',
                    borderRadius: 10,
                    border: `1.5px solid ${on ? t.forest : t.rule}`,
                    background: on ? t.forest : t.paper,
                    cursor: 'pointer',
                    transition: 'all .15s',
                    fontFamily: 'inherit',
                  }}
                >
                  <div style={{
                    fontFamily: t.serifDisp, fontSize: 15, fontWeight: 700,
                    marginBottom: 3, color: on ? '#fff' : t.ink,
                  }}>{opt.title}</div>
                  <div style={{
                    fontSize: 12, lineHeight: 1.4,
                    color: on ? 'rgba(255,255,255,.82)' : t.muted,
                    fontFamily: t.serifBody,
                  }}>{opt.desc}</div>
                </button>
              );
            })}
          </div>
        </Section>

        {/* Scope — segmented tabs + contextual input */}
        <Section label="Scope">
          <div style={nqS.tabRow}>
            {scopeTabs.map(tab => {
              const on = scopeKind === tab.v;
              return (
                <button
                  key={tab.v}
                  onClick={() => !tab.disabled && setScopeKind(tab.v)}
                  disabled={tab.disabled}
                  style={{
                    flex: 1,
                    padding: '9px 4px',
                    background: on ? t.paper : 'transparent',
                    border: 'none',
                    borderRadius: 7,
                    fontFamily: t.serifBody,
                    fontSize: 13,
                    fontWeight: on ? 700 : 500,
                    color: tab.disabled ? '#C4B89E' : on ? t.forestDk : t.muted,
                    cursor: tab.disabled ? 'not-allowed' : 'pointer',
                    boxShadow: on ? '0 1px 3px rgba(26,23,20,0.08)' : 'none',
                    transition: 'all .15s',
                  }}
                >{tab.label}</button>
              );
            })}
          </div>

          <div style={nqS.tabPanel}>
            {scopeKind === 'whole' && (
              <div style={nqS.tabHint}>
                Questions will pull from anywhere in this chapter.
              </div>
            )}

            {scopeKind === 'pages' && (
              <div>
                <div style={nqS.pagesRow}>
                  <PageInput
                    value={pageFrom}
                    min={chapter.pageStart}
                    max={chapter.pageEnd}
                    onChange={setPageFrom}
                  />
                  <span style={nqS.pageDash}>to</span>
                  <PageInput
                    value={pageTo}
                    min={chapter.pageStart}
                    max={chapter.pageEnd}
                    onChange={setPageTo}
                  />
                </div>
                <div style={nqS.tabHint}>
                  Chapter spans pp.&nbsp;{chapter.pageStart}–{chapter.pageEnd}.
                </div>
              </div>
            )}

            {scopeKind === 'topic' && (
              <div>
                <input
                  autoFocus
                  style={nqS.textInput}
                  placeholder="e.g. transferred intent, pre-existing duty rule"
                  value={topic}
                  onChange={e => setTopic(e.target.value)}
                />
                <div style={nqS.tabHint}>
                  Free-text focus. Generation will favor passages matching this topic.
                </div>
              </div>
            )}

            {scopeKind === 'case' && (
              cases.length === 0 ? (
                <div style={nqS.tabHint}>
                  No cases detected in this chapter.
                </div>
              ) : (
                <div>
                  <div style={nqS.selectWrap}>
                    <select
                      style={nqS.select}
                      value={caseId}
                      onChange={e => setCaseId(e.target.value)}
                    >
                      {cases.map(c => (
                        <option key={c.id} value={c.id}>{c.name}</option>
                      ))}
                    </select>
                    <span style={nqS.selectChev}>▾</span>
                  </div>
                  <div style={nqS.tabHint}>
                    {cases.find(c => c.id === caseId)?.cite || ''}
                  </div>
                </div>
              )
            )}
          </div>
        </Section>

      </div>

      <div style={nqS.actions}>
        <button style={nqS.btnGhost}   onClick={onCancel}>Cancel</button>
        <button style={nqS.btnPrimary} onClick={submit}>Generate quiz</button>
      </div>
    </Modal>
  );
}

// ── Section ─────────────────────────────────────────────────────────────────
function Section({ label, children }) {
  const t = window.LexTokens;
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{
        fontSize: 10.5, letterSpacing: '1.8px', textTransform: 'uppercase',
        color: t.forest, fontWeight: 700, marginBottom: 11,
      }}>{label}</div>
      {children}
    </div>
  );
}

// ── Counter ─────────────────────────────────────────────────────────────────
function Counter({ value, onChange, min, max }) {
  const t = window.LexTokens;
  function clamp(n) { return Math.max(min, Math.min(max, n)); }
  return (
    <div style={{ display:'flex', alignItems:'center', gap: 12 }}>
      <div style={{
        display:'inline-flex', alignItems:'stretch',
        border: `1.5px solid ${t.rule}`, borderRadius: 10,
        overflow: 'hidden', background: t.paper,
      }}>
        <button
          onClick={() => onChange(clamp(Number(value) - 1))}
          style={cBtn(t)}
          aria-label="Decrease"
        >−</button>
        <input
          type="text" inputMode="numeric"
          value={value}
          onChange={e => {
            const raw = e.target.value.replace(/[^0-9]/g, '');
            onChange(raw === '' ? '' : clamp(Number(raw)));
          }}
          onBlur={e => { if (e.target.value === '') onChange(min); }}
          style={{
            width: 56, padding: '0', textAlign:'center',
            border: 'none',
            borderLeft: `1px solid ${t.rule}`,
            borderRight: `1px solid ${t.rule}`,
            fontFamily: t.serifDisp, fontSize: 18, fontWeight: 700,
            color: t.ink, background: t.paper, outline: 'none',
          }}
        />
        <button
          onClick={() => onChange(clamp(Number(value) + 1))}
          style={cBtn(t)}
          aria-label="Increase"
        >+</button>
      </div>
      <span style={{ fontSize: 12.5, color: t.muted, fontFamily: t.serifBody, fontStyle: 'italic' }}>
        between {min} and {max}
      </span>
    </div>
  );
}
function cBtn(t) {
  return {
    width: 38, height: 40, background: t.paper, border: 'none',
    fontSize: 18, color: t.ink, cursor: 'pointer', lineHeight: 1,
    fontFamily: 'inherit',
  };
}

// ── PageInput ───────────────────────────────────────────────────────────────
function PageInput({ value, min, max, onChange }) {
  const t = window.LexTokens;
  return (
    <input
      type="text" inputMode="numeric"
      value={value}
      onChange={e => {
        const raw = e.target.value.replace(/[^0-9]/g, '');
        if (raw === '') return onChange('');
        const n = Math.max(min, Math.min(max, Number(raw)));
        onChange(n);
      }}
      onBlur={e => { if (e.target.value === '') onChange(min); }}
      style={{
        width: 72, padding: '9px 12px', textAlign: 'center',
        borderRadius: 8, border: `1.5px solid ${t.rule}`,
        fontFamily: t.serifDisp, fontSize: 15, fontWeight: 700, color: t.ink,
        outline: 'none', background: t.paper,
      }}
    />
  );
}

// ── Styles ──────────────────────────────────────────────────────────────────
const nqT = window.LexTokens;
const nqS = {
  body: { paddingTop: 4 },

  styleGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 },

  // Tab row — looks like a segmented control sitting in a soft pill
  tabRow: {
    display: 'flex', gap: 4, padding: 4,
    background: nqT.cream, borderRadius: 10,
    border: `1px solid ${nqT.ruleSoft}`,
  },
  tabPanel: {
    marginTop: 14, padding: '14px 14px 12px',
    background: nqT.paper, borderRadius: 10,
    border: `1px solid ${nqT.rule}`,
    minHeight: 76, display: 'flex', flexDirection: 'column', justifyContent: 'center',
  },
  tabHint: {
    fontSize: 12.5, color: nqT.muted, fontFamily: nqT.serifBody,
    fontStyle: 'italic', lineHeight: 1.5, marginTop: 8,
  },

  pagesRow: { display: 'flex', alignItems: 'center', gap: 12 },
  pageDash: { fontSize: 13, color: nqT.muted, fontFamily: nqT.serifBody },

  textInput: {
    width: '100%', padding: '10px 14px', borderRadius: 8,
    border: `1.5px solid ${nqT.rule}`, fontSize: 14, fontFamily: nqT.serifBody,
    outline: 'none', background: nqT.paper, color: nqT.ink,
    boxSizing: 'border-box',
  },

  selectWrap: { position: 'relative', width: '100%' },
  select: {
    width: '100%', padding: '10px 36px 10px 14px',
    borderRadius: 8, border: `1.5px solid ${nqT.rule}`,
    fontSize: 14, fontFamily: nqT.serifBody,
    background: nqT.paper, outline: 'none',
    appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
    color: nqT.ink, boxSizing: 'border-box',
    textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden',
  },
  selectChev: {
    position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)',
    fontSize: 11, color: nqT.muted, pointerEvents: 'none',
  },

  flag: { color: nqT.gold, fontWeight: 600, fontStyle: 'normal' },

  actions: {
    display: 'flex', justifyContent: 'flex-end', gap: 10,
    paddingTop: 18, marginTop: 4, borderTop: `1px solid ${nqT.ruleSoft}`,
  },
  btnPrimary: {
    padding: '11px 22px', background: nqT.forest, color: 'white',
    border: 'none', borderRadius: 9, fontSize: 14, fontWeight: 600,
    cursor: 'pointer', fontFamily: 'inherit', letterSpacing: '.2px',
  },
  btnGhost: {
    padding: '11px 18px', background: 'none', color: nqT.ink,
    border: `1px solid ${nqT.rule}`, borderRadius: 9, fontSize: 14,
    fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
  },
};

Object.assign(window, { NewQuizModal });
