// Team dashboard — edit Written Response + Take-home Case prompts.

function FieldLabel({ children, hint }) {
  return (
    <div style={{ marginBottom: 8 }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: T.ink }}>{children}</div>
      {hint && <div style={{ fontSize: 12.5, color: T.muted, marginTop: 4, lineHeight: 1.45 }}>{hint}</div>}
    </div>
  );
}

function TextArea({ value, onChange, rows = 5, placeholder }) {
  return (
    <textarea value={value} onChange={(e) => onChange(e.target.value)} rows={rows} placeholder={placeholder}
      style={{ width: '100%', boxSizing: 'border-box', padding: '12px 14px', borderRadius: 12,
        border: `1px solid ${T.lineStrong}`, fontFamily: FONT, fontSize: 14.5, lineHeight: 1.55,
        color: T.ink, background: T.white, resize: 'vertical', minHeight: 120 }} />
  );
}

function TextInput({ value, onChange, placeholder, type = 'text' }) {
  return (
    <input type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
      style={{ width: '100%', boxSizing: 'border-box', padding: '11px 14px', borderRadius: 12,
        border: `1px solid ${T.lineStrong}`, fontFamily: FONT, fontSize: 14.5, color: T.ink, background: T.white }} />
  );
}

function NumInput({ value, onChange, min, max }) {
  return (
    <input type="number" value={value} min={min} max={max} onChange={(e) => onChange(parseInt(e.target.value, 10) || 0)}
      style={{ width: 110, boxSizing: 'border-box', padding: '11px 14px', borderRadius: 12,
        border: `1px solid ${T.lineStrong}`, fontFamily: FONT, fontSize: 14.5, color: T.ink, background: T.white }} />
  );
}

function StagePrompts({ useLive }) {
  const defaults = {
    written: window.WWFunnel?.normalizeWrittenConfig(window.WWData?.QUESTIONS?.written) || { prompts: [], minWords: 150, maxWords: 300 },
    case: { ...(window.WWData?.QUESTIONS?.case || {}) },
  };

  const [written, setWritten] = React.useState(defaults.written);
  const [casePrompt, setCasePrompt] = React.useState(defaults.case);
  const [loading, setLoading] = React.useState(!!useLive);
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    if (!useLive) return;
    (async () => {
      try {
        const prompts = await WWAdmin.fetchStagePrompts();
        if (prompts.written) setWritten(window.WWFunnel?.normalizeWrittenConfig(prompts.written) || prompts.written);
        if (prompts.case) setCasePrompt(prompts.case);
      } catch (err) {
        setError(err.message || 'Could not load prompts.');
      } finally {
        setLoading(false);
      }
    })();
  }, [useLive]);

  const handleSave = async () => {
    setError('');
    setSaved(false);
    if (!useLive) {
      alert('Connect Supabase to save prompt changes for applicants.');
      return;
    }
    setSaving(true);
    try {
      await WWAdmin.saveStagePrompts({ written, case: casePrompt });
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      setError(err.message || 'Save failed.');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div style={{ padding: 40 }}>
        <div style={{ fontSize: 15, color: T.muted }}>Loading prompts…</div>
      </div>
    );
  }

  return (
    <div style={{ padding: '32px 36px 48px', maxWidth: 820 }}>
      <Eyebrow>Program settings</Eyebrow>
      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 32, letterSpacing: '-0.03em', margin: '10px 0 8px' }}>
        Stage prompts
      </h1>
      <p style={{ fontSize: 15, color: T.muted, lineHeight: 1.55, maxWidth: 560, marginBottom: 28 }}>
        Update the questions applicants see for the Written Response and Take-home Case stages. Changes apply immediately for new sessions.
      </p>

      {error && (
        <div style={{ marginBottom: 20, padding: '12px 16px', borderRadius: 12, background: T.redSoft, color: T.red, fontSize: 14 }}>
          {error}
        </div>
      )}

      <Card style={{ marginBottom: 24 }}>
        <Eyebrow color={T.orangeDeep} style={{ marginBottom: 6 }}>Written response</Eyebrow>
        <h2 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 22, margin: '0 0 18px' }}>Essay prompts</h2>
        <p style={{ fontSize: 14, color: T.muted, lineHeight: 1.5, marginBottom: 18 }}>
          Applicants answer each essay separately. Reviewers score each one on its own.
        </p>
        {(written.prompts || []).map((essay, idx) => (
          <Card key={essay.id || idx} pad={18} style={{ marginBottom: 14, background: T.panel }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <Eyebrow>Essay {idx + 1}</Eyebrow>
              {(written.prompts || []).length > 1 && (
                <Btn variant="ghost" size="sm" onClick={() => setWritten((w) => ({
                  ...w,
                  prompts: w.prompts.filter((_, i) => i !== idx),
                }))}>Remove</Btn>
              )}
            </div>
            <div style={{ marginBottom: 14 }}>
              <FieldLabel>Title</FieldLabel>
              <TextInput value={essay.title || ''} onChange={(v) => setWritten((w) => ({
                ...w,
                prompts: w.prompts.map((p, i) => i === idx ? { ...p, title: v } : p),
              }))} />
            </div>
            <FieldLabel hint="Shown to applicants before they write this essay.">Prompt</FieldLabel>
            <TextArea value={essay.prompt || ''} onChange={(v) => setWritten((w) => ({
              ...w,
              prompts: w.prompts.map((p, i) => i === idx ? { ...p, prompt: v } : p),
            }))} rows={5} />
          </Card>
        ))}
        <Btn variant="ghost" icon="plus" onClick={() => setWritten((w) => ({
          ...w,
          prompts: [...(w.prompts || []), {
            id: `essay-${Date.now()}`,
            title: 'New essay',
            prompt: '',
          }],
        }))} style={{ marginBottom: 18 }}>Add essay</Btn>
        <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
          <div>
            <FieldLabel>Minimum words</FieldLabel>
            <NumInput value={written.minWords || 0} min={50} max={500} onChange={(v) => setWritten((w) => ({ ...w, minWords: v }))} />
          </div>
          <div>
            <FieldLabel>Maximum words</FieldLabel>
            <NumInput value={written.maxWords || 0} min={100} max={1000} onChange={(v) => setWritten((w) => ({ ...w, maxWords: v }))} />
          </div>
        </div>
      </Card>

      <Card style={{ marginBottom: 28 }}>
        <Eyebrow color={T.blue} style={{ marginBottom: 6 }}>Take-home case</Eyebrow>
        <h2 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 22, margin: '0 0 18px' }}>Case brief</h2>
        <div style={{ marginBottom: 18 }}>
          <FieldLabel>Title</FieldLabel>
          <TextInput value={casePrompt.title || ''} onChange={(v) => setCasePrompt((c) => ({ ...c, title: v }))} />
        </div>
        <div style={{ marginBottom: 18 }}>
          <FieldLabel hint="The full instructions applicants receive for the memo.">
            Brief
          </FieldLabel>
          <TextArea value={casePrompt.brief || ''} onChange={(v) => setCasePrompt((c) => ({ ...c, brief: v }))} rows={7} />
        </div>
        <div>
          <FieldLabel hint="Displayed on the case intro screen (e.g. 48 hours).">
            Submission window
          </FieldLabel>
          <TextInput value={casePrompt.window || ''} onChange={(v) => setCasePrompt((c) => ({ ...c, window: v }))} />
        </div>
      </Card>

      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <Btn onClick={handleSave} disabled={saving} icon="check">
          {saving ? 'Saving…' : 'Save prompts'}
        </Btn>
        {saved && <span style={{ fontSize: 14, fontWeight: 600, color: T.green }}>Saved — applicants will see the updated prompts.</span>}
      </div>
    </div>
  );
}

Object.assign(window, { StagePrompts });
