"use client";
import { useEffect, useMemo, useState } from 'react';

/* Structured prompt sections compose into a single markdown string. The
   marker on the first line lets us know the saved string was generated
   here so re-opening the modal can re-parse it back into the form. */
const STRUCTURED_MARKER = '<!-- madarx:structured-v1 -->';

const ROLE_ARCHETYPES = [
  { id: 'cos', label: 'Chief of Staff', tagline: 'Serves the principal, oversees all agents. (Default for madarX.)' },
  { id: 'ceo', label: 'CEO', tagline: 'Sets strategy, delegates execution.' },
  { id: 'cto', label: 'CTO', tagline: 'Owns backend, infra, security.' },
  { id: 'cpo', label: 'CPO', tagline: 'Owns product lifecycle end-to-end.' },
  { id: 'designer', label: 'Designer', tagline: 'Frontend and UI implementation.' },
  { id: 'researcher', label: 'Researcher', tagline: 'Discovers, learns, reports.' },
  { id: 'custom', label: 'Custom', tagline: 'No preset — write your own below.' },
];

/* Pre-filled defaults for each role archetype. Applied only when the user
   clicks "Apply preset" so accidental archetype clicks never wipe their
   custom content. `custom` has no preset by design. */
const ARCHETYPE_PRESETS = {
  cos: {
    role: 'You are madarX — the Chief of Staff to the principal (the human owner of this machine). You are a local-first orchestrator that oversees every other agent on this system. Your job is to translate the principal\'s intent into action: decide what to do yourself, what to delegate, and what to escalate. You report up to the principal as a chief of staff reports to a chairman — you bring back the actual answer, not a list of places they could go to find it.',
    delegation: 'Recurring / scheduled work → create a specialist agent and assign\nOne-off lookups, research, comparisons → do it yourself with web_search + web_fetch + generate_ui\nLong-running or multi-step builds → start_hermes_job\nIrreversible external action (deploy, send, merge) → draft and route to the principal for approval',
    doList: [
      'Translate the principal\'s intent into a concrete plan.',
      'Oversee every other agent — see their work, unblock them, coordinate cross-agent tasks.',
      'Pick the right tool: web_search / web_fetch for lookups, generate_ui for visual output, create_agent only for recurring work.',
      'Bring back final answers, not lists of links. Render structured results as artifacts.',
      'Escalate to the principal anything irreversible, ambiguous, or out of scope.',
    ],
    neverList: [
      'Auto-execute destructive or irreversible commands without approval.',
      'Dump long markdown into the chat — always render as an artifact.',
      'Create an agent for a one-off question — answer it yourself.',
      'Use emojis anywhere in output.',
    ],
  },
  ceo: {
    role: 'You are the CEO. You own strategy, prioritization, and cross-functional coordination. You do NOT do individual-contributor work — you delegate to your direct reports.',
    delegation: 'Websites / web apps / user-facing work → CPO\nSecurity / infra / backend bugs → CTO\nMarketing / content / growth → CMO\nUX research / design-system governance → UXDesigner\nCross-functional or unclear → CPO',
    doList: [
      'Set priorities and make product decisions.',
      'Resolve cross-team conflicts or ambiguity.',
      'Communicate with the board (human users).',
      'Approve or reject proposals from direct reports.',
      'Hire new agents when the team needs capacity.',
    ],
    neverList: [
      'Build websites, apps, or any product yourself — delegate to CPO.',
      'Write code, fix bugs, or implement features — delegate to CTO.',
      'Create marketing content — delegate to CMO.',
      'Design interfaces or user flows — delegate to UXDesigner.',
    ],
  },
  cto: {
    role: 'You are the CTO. You own technical direction — backend, APIs, infrastructure, security, CI/CD. You implement what only you can implement, and delegate UI / product / content work upstream.',
    delegation: 'Frontend / UI / page work → WebDesigner or CPO\nProduct strategy / scope → CPO\nMarketing copy → CMO',
    doList: [
      'Design and implement backend services and APIs.',
      'Own security posture, secrets, and access control.',
      'Maintain CI/CD pipelines and deploy infrastructure.',
      'Review high-risk technical changes before merge.',
    ],
    neverList: [
      'Build marketing pages or product UI — delegate.',
      'Make product scope decisions unilaterally — escalate to CPO.',
      'Skip security review on irreversible_external changes.',
    ],
  },
  cpo: {
    role: 'You are the CPO. You own the full product lifecycle end-to-end — websites, web apps, landing pages, user-facing deliverables. Run the /deliver pipeline (plan → build → security → perf → QA → design → review → docs → PR → deploy → canary).',
    delegation: 'Backend / infra-only work → CTO\nFrontend implementation → WebDesigner\nMarketing assets → CMO',
    doList: [
      'Define product scope, milestones, and acceptance criteria.',
      'Run /deliver from spec to deployed artifact.',
      'Coordinate between CTO and design for cross-cutting work.',
      'Sign off on QA + canary before declaring shipped.',
    ],
    neverList: [
      'Ship without QA and canary verification.',
      'Bypass approval gates for irreversible_external actions.',
    ],
  },
  designer: {
    role: 'You are the Web Designer. You own frontend / UI implementation. You translate product specs into production HTML / CSS / components using the project design system.',
    delegation: 'Backend or data work → CTO\nProduct scope changes → CPO',
    doList: [
      'Implement frontend components matching the design system.',
      'Use proper SVG icons (Lucide / Heroicons / Phosphor) — never emojis.',
      'Test responsive behavior at mobile, tablet, desktop.',
      'Hand off to CPO for QA + deploy.',
    ],
    neverList: [
      'Use emojis as UI icons.',
      'Ship a default Inter / Roboto / Arial stack without design justification.',
      'Use gradient text outside the approved system.',
    ],
  },
  researcher: {
    role: 'You are the Researcher. You discover, summarize, and report. Output is structured findings — not opinions, not actions.',
    delegation: 'Anything actionable → flag for the relevant team lead\nUI rendering of findings → designer',
    doList: [
      'Search the web and synthesize structured summaries.',
      'Cite every claim with a source URL.',
      'Quantify uncertainty when sources disagree.',
      'Render findings as artifacts (report / dashboard), not chat blobs.',
    ],
    neverList: [
      'Make decisions or take actions on behalf of the user.',
      'Fabricate sources or numbers.',
    ],
  },
};

const PERSONALITIES = [
  { id: 'formal', label: 'Formal', desc: 'Precise, structured, businesslike.' },
  { id: 'friendly', label: 'Friendly', desc: 'Warm, conversational, encouraging.' },
  { id: 'direct', label: 'Direct', desc: 'Terse, blunt, fragments OK.' },
  { id: 'analytical', label: 'Analytical', desc: 'Data-first, weighs trade-offs.' },
  { id: 'visionary', label: 'Visionary', desc: 'Big-picture, possibility-oriented.' },
  { id: 'warm', label: 'Warm', desc: 'Empathetic, supportive, patient.' },
];

const DEFAULT_DO = [
  'Set priorities and make product decisions.',
  'Resolve cross-team conflicts or ambiguity.',
  'Communicate with the board (human users).',
  'Approve or reject proposals from direct reports.',
];
const DEFAULT_NEVER = [
  'Build, code, or fix bugs yourself — delegate instead.',
  'Create marketing content — delegate to the CMO.',
  'Design interfaces or user flows — delegate to the designer.',
];
const DEFAULT_SAFETY = [
  'Never exfiltrate secrets or private data.',
  'Do not perform destructive commands unless explicitly requested.',
];
const DEFAULT_REFERENCES = [
  './HEARTBEAT.md',
  './SOUL.md',
  './TOOLS.md',
];

/* Tiny inline SVG illustrations per archetype + personality.
   No emojis (per global UI rules). All single-stroke marks at 24px. */
function ArchetypeMark({ id }) {
  const stroke = 'currentColor';
  switch (id) {
    case 'cos':
      return (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <circle cx="12" cy="8" r="3.2" />
          <path d="M5 20c0-3.6 3.1-6 7-6s7 2.4 7 6" />
          <path d="M16.5 4.5l1.5 1.5-1.5 1.5" />
        </svg>
      );
    case 'ceo':
      return (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <path d="M4 18l4-8 4 4 4-6 4 10" />
          <circle cx="20" cy="6" r="1.6" fill={stroke} stroke="none" />
        </svg>
      );
    case 'cto':
      return (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <path d="M8 8l-4 4 4 4" /><path d="M16 8l4 4-4 4" /><path d="M13 5l-2 14" />
        </svg>
      );
    case 'cpo':
      return (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <rect x="4" y="5" width="16" height="14" rx="2" />
          <path d="M4 9h16" /><path d="M9 13h6" />
        </svg>
      );
    case 'designer':
      return (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <circle cx="12" cy="12" r="8" />
          <circle cx="9" cy="9.5" r="1.1" fill={stroke} stroke="none" />
          <circle cx="15" cy="9.5" r="1.1" fill={stroke} stroke="none" />
          <circle cx="8" cy="13.5" r="1.1" fill={stroke} stroke="none" />
        </svg>
      );
    case 'researcher':
      return (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <circle cx="11" cy="11" r="6" />
          <path d="M20 20l-4.5-4.5" />
        </svg>
      );
    default:
      return (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <path d="M5 12h14" /><path d="M12 5v14" />
        </svg>
      );
  }
}

function PersonalityMark({ id }) {
  const stroke = 'currentColor';
  switch (id) {
    case 'formal':
      return <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" aria-hidden><rect x="4" y="4" width="16" height="16" rx="1" /><path d="M4 12h16" /></svg>;
    case 'friendly':
      return <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden><circle cx="12" cy="12" r="8" /><path d="M9 14c.8 1 2 1.6 3 1.6S14.2 15 15 14" /><circle cx="9" cy="10" r=".9" fill={stroke} stroke="none" /><circle cx="15" cy="10" r=".9" fill={stroke} stroke="none" /></svg>;
    case 'direct':
      return <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" aria-hidden><path d="M4 12h14" /><path d="M14 7l5 5-5 5" /></svg>;
    case 'analytical':
      return <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden><path d="M4 20V8" /><path d="M10 20V4" /><path d="M16 20v-9" /><path d="M22 20H2" /></svg>;
    case 'visionary':
      return <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden><circle cx="12" cy="12" r="3" /><path d="M2 12s3.6-6 10-6 10 6 10 6-3.6 6-10 6S2 12 2 12z" /></svg>;
    case 'warm':
      return <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden><path d="M12 21s-7-4.5-7-10a4 4 0 017-2.6A4 4 0 0119 11c0 5.5-7 10-7 10z" /></svg>;
    default:
      return null;
  }
}

function parseStructured(raw) {
  if (!raw || !raw.startsWith(STRUCTURED_MARKER)) return null;
  const body = raw.slice(STRUCTURED_MARKER.length).trim();
  const section = (header) => {
    const re = new RegExp(`(^|\\n)##\\s+${header}\\s*\\n([\\s\\S]*?)(?=\\n##\\s+|$)`, 'i');
    const m = body.match(re);
    return m ? m[2].trim() : '';
  };
  const bullets = (text) => text.split('\n').map(l => l.replace(/^[-*]\s+/, '').trim()).filter(Boolean);

  const roleHeader = body.match(/^#\s+(.+?)\s*\n([\s\S]*?)(?=\n##\s+|$)/);
  const archMatch = body.match(/<!--\s*archetype:(\w+)\s*-->/);
  const persMatch = body.match(/<!--\s*personality:(\w+)\s*-->/);

  const reportsRaw = section('Direct Reports');
  const reportLines = reportsRaw.split('\n').filter(l => l.startsWith('|') && !l.includes('---') && !/Role\s*\|\s*Agent/.test(l));
  const reports = reportLines.map(l => {
    const cells = l.split('|').map(c => c.trim()).filter(Boolean);
    if (cells.length < 2) return null;
    const role = cells[0].replace(/\*\*/g, '');
    const idCell = cells[1].replace(/`/g, '');
    const resp = cells[2] || '';
    return { role, agentId: idCell, responsibility: resp };
  }).filter(Boolean);

  return {
    archetype: archMatch?.[1] || 'custom',
    personality: persMatch?.[1] || 'direct',
    role: roleHeader?.[2]?.trim() || '',
    delegation: section('Delegation'),
    doList: bullets(section('What you DO personally')),
    neverList: bullets(section('What you NEVER do')),
    safetyList: bullets(section('Safety')),
    references: bullets(section('References')).map(s => s.replace(/^`|`$/g, '')),
    reports,
  };
}

function composeStructured(form) {
  const lines = [STRUCTURED_MARKER, ''];
  lines.push(`<!-- archetype:${form.archetype} -->`);
  lines.push(`<!-- personality:${form.personality} -->`);
  lines.push('');
  lines.push(`# Role`);
  lines.push(form.role.trim() || '(undefined)');
  lines.push('');
  const persona = PERSONALITIES.find(p => p.id === form.personality);
  if (persona) {
    lines.push(`## Personality`);
    lines.push(`${persona.label} — ${persona.desc}`);
    lines.push('');
  }
  if (form.reports.length) {
    lines.push(`## Your Direct Reports`);
    lines.push(`| Role | Agent ID | Responsibility |`);
    lines.push(`|------|----------|---------------|`);
    for (const r of form.reports) {
      lines.push(`| **${r.role}** | \`${r.agentId}\` | ${r.responsibility} |`);
    }
    lines.push('');
  }
  if (form.delegation.trim()) {
    lines.push(`## Delegation`);
    lines.push(form.delegation.trim());
    lines.push('');
  }
  if (form.doList.length) {
    lines.push(`## What you DO personally`);
    for (const item of form.doList) lines.push(`- ${item}`);
    lines.push('');
  }
  if (form.neverList.length) {
    lines.push(`## What you NEVER do`);
    for (const item of form.neverList) lines.push(`- ${item}`);
    lines.push('');
  }
  if (form.safetyList.length) {
    lines.push(`## Safety`);
    for (const item of form.safetyList) lines.push(`- ${item}`);
    lines.push('');
  }
  if (form.references.length) {
    lines.push(`## References`);
    for (const item of form.references) lines.push(`- \`${item}\``);
    lines.push('');
  }
  return lines.join('\n').trim() + '\n';
}

function EditableChipList({ label, items, onChange, placeholder }) {
  const [draft, setDraft] = useState('');
  function add() {
    const v = draft.trim();
    if (!v) return;
    onChange([...items, v]);
    setDraft('');
  }
  function remove(i) {
    onChange(items.filter((_, idx) => idx !== i));
  }
  return (
    <div className="instr-chiplist">
      <div className="instr-chiplist-label">{label}</div>
      {items.length > 0 && (
        <ul className="instr-chiplist-items">
          {items.map((it, i) => (
            <li key={i}>
              <span>{it}</span>
              <button type="button" onClick={() => remove(i)} aria-label={`Remove ${it}`}>×</button>
            </li>
          ))}
        </ul>
      )}
      <div className="instr-chiplist-add">
        <input
          type="text"
          value={draft}
          placeholder={placeholder}
          onChange={e => setDraft(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); add(); } }}
        />
        <button type="button" onClick={add} disabled={!draft.trim()}>Add</button>
      </div>
    </div>
  );
}

export default function InstructionsBuilder({
  value,
  onChange,
  onSave,
  saving,
  agents = [],
}) {
  const parsed = useMemo(() => parseStructured(value), [value]);
  const [mode, setMode] = useState('structured');
  const [showPreview, setShowPreview] = useState(false);
  const [form, setForm] = useState(() => parsed || {
    archetype: 'cos',
    personality: 'direct',
    role: ARCHETYPE_PRESETS.cos.role,
    delegation: ARCHETYPE_PRESETS.cos.delegation,
    doList: [...ARCHETYPE_PRESETS.cos.doList],
    neverList: [...ARCHETYPE_PRESETS.cos.neverList],
    safetyList: [...DEFAULT_SAFETY],
    references: [...DEFAULT_REFERENCES],
    reports: [],
  });

  useEffect(() => {
    if (parsed) setForm(parsed);
  }, [parsed]);

  function update(patch) {
    setForm(prev => ({ ...prev, ...patch }));
  }

  function applyPreset(archetypeId) {
    const preset = ARCHETYPE_PRESETS[archetypeId];
    if (!preset) return;
    update({
      archetype: archetypeId,
      role: preset.role,
      delegation: preset.delegation,
      doList: [...preset.doList],
      neverList: [...preset.neverList],
    });
  }

  function presetMatchesForm() {
    const preset = ARCHETYPE_PRESETS[form.archetype];
    if (!preset) return true; // 'custom' or unknown — nothing to apply
    return (
      form.role === preset.role &&
      form.delegation === preset.delegation &&
      form.doList.length === preset.doList.length &&
      form.doList.every((v, i) => v === preset.doList[i]) &&
      form.neverList.length === preset.neverList.length &&
      form.neverList.every((v, i) => v === preset.neverList[i])
    );
  }

  function addReport(agent) {
    if (!agent) return;
    if (form.reports.some(r => r.agentId === agent.id)) return;
    update({
      reports: [
        ...form.reports,
        { role: agent.name || agent.id, agentId: agent.id, responsibility: '' },
      ],
    });
  }
  function patchReport(i, patch) {
    update({ reports: form.reports.map((r, idx) => idx === i ? { ...r, ...patch } : r) });
  }
  function removeReport(i) {
    update({ reports: form.reports.filter((_, idx) => idx !== i) });
  }

  function saveStructured() {
    const composed = composeStructured(form);
    onChange(composed);
    onSave();
  }
  function saveRaw() {
    onSave();
  }

  const availableAgents = agents.filter(a => !form.reports.some(r => r.agentId === a.id));
  const archetypeHasPreset = !!ARCHETYPE_PRESETS[form.archetype];
  const presetIsApplied = archetypeHasPreset && presetMatchesForm();

  return (
    <div className="instr-builder">
      <div className="instr-mode-toggle" role="tablist" aria-label="Instructions editor mode">
        <button
          type="button"
          role="tab"
          aria-selected={mode === 'structured'}
          className={'instr-mode-pill' + (mode === 'structured' ? ' on' : '')}
          onClick={() => setMode('structured')}
        >Structured</button>
        <button
          type="button"
          role="tab"
          aria-selected={mode === 'raw'}
          className={'instr-mode-pill' + (mode === 'raw' ? ' on' : '')}
          onClick={() => setMode('raw')}
        >Raw markdown</button>
      </div>

      {mode === 'structured' ? (
        <div className="instr-form">
          <section className="instr-section">
            <header className="instr-section-head">
              <h4>Role archetype</h4>
              <p>Templates seed the Role, Delegation, DO, and NEVER fields below. Clicking a card only selects it — apply the preset with the button to overwrite. <b>Custom</b> applies nothing.</p>
            </header>
            <div className="instr-card-grid">
              {ROLE_ARCHETYPES.map(a => (
                <button
                  key={a.id}
                  type="button"
                  className={'instr-card' + (form.archetype === a.id ? ' on' : '')}
                  onClick={() => update({ archetype: a.id })}
                  aria-pressed={form.archetype === a.id}
                >
                  <span className="instr-card-mark"><ArchetypeMark id={a.id} /></span>
                  <span className="instr-card-body">
                    <b>{a.label}</b>
                    <small>{a.tagline}</small>
                  </span>
                </button>
              ))}
            </div>
            {archetypeHasPreset && (
              <div className={'instr-preset-banner' + (presetIsApplied ? ' applied' : '')}>
                {presetIsApplied ? (
                  <span><b>{ROLE_ARCHETYPES.find(x => x.id === form.archetype)?.label}</b> preset applied. Edit any field below to customize.</span>
                ) : (
                  <>
                    <span>Apply the <b>{ROLE_ARCHETYPES.find(x => x.id === form.archetype)?.label}</b> preset? Overwrites Role, Delegation, DO, and NEVER.</span>
                    <button type="button" className="config-save-btn" onClick={() => applyPreset(form.archetype)}>Apply preset</button>
                  </>
                )}
              </div>
            )}
            {!archetypeHasPreset && (
              <div className="instr-preset-banner">
                <span>No preset — define Role, Delegation, DO, and NEVER yourself below.</span>
              </div>
            )}
          </section>

          <section className="instr-section">
            <header className="instr-section-head">
              <h4>Personality</h4>
              <p>Adds a <code>## Personality</code> block to the composed prompt so the LLM matches this tone in its replies. Pure prompt hint — no other config changes.</p>
            </header>
            <div className="instr-card-grid">
              {PERSONALITIES.map(p => (
                <button
                  key={p.id}
                  type="button"
                  className={'instr-card' + (form.personality === p.id ? ' on' : '')}
                  onClick={() => update({ personality: p.id })}
                  aria-pressed={form.personality === p.id}
                >
                  <span className="instr-card-mark"><PersonalityMark id={p.id} /></span>
                  <span className="instr-card-body">
                    <b>{p.label}</b>
                    <small>{p.desc}</small>
                  </span>
                </button>
              ))}
            </div>
          </section>

          <section className="instr-section">
            <header className="instr-section-head">
              <h4>Role description</h4>
              <p>One paragraph. What this agent owns and how it operates.</p>
            </header>
            <textarea
              className="instr-textarea"
              rows={4}
              value={form.role}
              onChange={e => update({ role: e.target.value })}
              placeholder="You are the CEO. You own strategy, prioritization, and cross-functional coordination."
            />
          </section>

          <section className="instr-section">
            <header className="instr-section-head">
              <h4>Direct reports</h4>
              <p>Pulled from your installed agents. Pick who reports to this one and label their role.</p>
            </header>
            {form.reports.length > 0 ? (
              <div className="instr-reports">
                {form.reports.map((r, i) => (
                  <div key={r.agentId + i} className="instr-report-row">
                    <div className="instr-report-meta">
                      <input
                        type="text"
                        value={r.role}
                        onChange={e => patchReport(i, { role: e.target.value })}
                        placeholder="Role (e.g. CTO)"
                        className="instr-report-role"
                      />
                      <code className="instr-report-id">{r.agentId}</code>
                    </div>
                    <input
                      type="text"
                      value={r.responsibility}
                      onChange={e => patchReport(i, { responsibility: e.target.value })}
                      placeholder="Owns backend, infra, security."
                      className="instr-report-resp"
                    />
                    <button type="button" className="instr-report-remove" onClick={() => removeReport(i)} aria-label="Remove report">×</button>
                  </div>
                ))}
              </div>
            ) : (
              <div className="instr-empty">No reports yet. Add an agent below.</div>
            )}
            {availableAgents.length > 0 && (
              <div className="instr-report-add">
                <select onChange={e => { const a = agents.find(x => x.id === e.target.value); addReport(a); e.target.value = ''; }} defaultValue="">
                  <option value="" disabled>Add an agent as report…</option>
                  {availableAgents.map(a => (
                    <option key={a.id} value={a.id}>{a.name || a.id}</option>
                  ))}
                </select>
              </div>
            )}
          </section>

          <section className="instr-section">
            <header className="instr-section-head">
              <h4>Delegation rules</h4>
              <p>How tasks are routed. Use plain bullets or short paragraphs.</p>
            </header>
            <textarea
              className="instr-textarea"
              rows={5}
              value={form.delegation}
              onChange={e => update({ delegation: e.target.value })}
              placeholder={'Websites / web apps / user-facing work → CPO\nSecurity / infra / backend bugs → CTO\nCross-functional or unclear → CPO'}
            />
          </section>

          <div className="instr-two-col">
            <EditableChipList
              label="What you DO personally"
              items={form.doList}
              onChange={items => update({ doList: items })}
              placeholder="Add a responsibility…"
            />
            <EditableChipList
              label="What you NEVER do"
              items={form.neverList}
              onChange={items => update({ neverList: items })}
              placeholder="Add an anti-task…"
            />
          </div>

          <div className="instr-two-col">
            <EditableChipList
              label="Safety"
              items={form.safetyList}
              onChange={items => update({ safetyList: items })}
              placeholder="Add a safety constraint…"
            />
            <EditableChipList
              label="References"
              items={form.references}
              onChange={items => update({ references: items })}
              placeholder="./FILE.md"
            />
          </div>

          <section className="instr-section">
            <header className="instr-section-head">
              <h4>Composed prompt preview</h4>
              <p>This is the exact markdown that will be saved as the system prompt when you hit Save. Toggle open to verify before saving.</p>
            </header>
            <button
              type="button"
              className="instr-preview-toggle"
              onClick={() => setShowPreview(v => !v)}
              aria-expanded={showPreview}
            >
              {showPreview ? 'Hide preview' : 'Show preview'}
            </button>
            {showPreview && (
              <pre className="instr-preview">{composeStructured(form)}</pre>
            )}
          </section>

          <div className="config-footer">
            <span className="config-char-count">{composeStructured(form).length} chars (composed)</span>
            <button className="config-save-btn" onClick={saveStructured} disabled={saving}>
              {saving ? 'Saving…' : 'Save Instructions'}
            </button>
          </div>
        </div>
      ) : (
        <div className="instr-raw">
          <textarea
            className="config-textarea"
            value={value}
            onChange={e => onChange(e.target.value)}
            spellCheck={false}
          />
          <div className="config-footer">
            <span className="config-char-count">{value.length} chars</span>
            <button className="config-save-btn" onClick={saveRaw} disabled={saving}>
              {saving ? 'Saving…' : 'Save Instructions'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
