// detail-modals.jsx — ComponentDetailModal + ComboDetailModal
const { useState, useContext, useEffect, useCallback } = React;

const COMP_STATUSES = ['Testing', 'Winner', 'Loser'];
const EDIT_STATUSES = ['Not Started', 'In Progress', 'Complete'];
const COMBO_STATUSES = ['Draft', 'Testing', 'Scaling', 'Winner', 'Loser', 'Paused'];

async function generateDescription(script, type) {
  if (!script || script.trim().length < 10) return '';
  const typeLabel = type === 'hook' ? 'Hook (opening of an ad)'
    : type === 'lead' ? 'Lead (bridge section of an ad)'
    : 'Body (main content of an ad)';
  const prompt = `You are labeling ad creative components for a media buying tracker. Given this ${typeLabel} script, write a single concise description of max 8 words that captures what this component does. Output only the description, no punctuation at the end, no quotes.

Script:
${script.slice(0, 800)}`;
  try {
    const result = await window.claude.complete(prompt);
    return result.trim().replace(/^["']|["']$/g, '');
  } catch(e) { return ''; }
}

function ComponentDetailModal({ itemId, onClose, onOpenComponent }) {
  const { state, dispatch } = useContext(window.AppCtx);
  const orig = state.components.find(c => c.id === itemId && c.workspaceId === state.activeWorkspaceId);
  const [form, setForm] = useState(orig ? { ...orig } : null);
  const [confirm, setConfirm] = useState(false);
  const [genLoading, setGenLoading] = useState(false);

  useEffect(() => {
    const c = state.components.find(c => c.id === itemId && c.workspaceId === state.activeWorkspaceId);
    if (c) setForm({ ...c });
  }, [itemId, state.components]);

  const regenDesc = useCallback(async (script, type) => {
    if (!script?.trim()) return;
    setGenLoading(true);
    const desc = await generateDescription(script, type);
    if (desc) setForm(f => ({ ...f, description: desc }));
    setGenLoading(false);
  }, []);

  const handleScriptBlur = useCallback((script, type, existingDesc) => {
    if (script?.trim() && !existingDesc) regenDesc(script, type);
  }, [regenDesc]);

  if (!form) return null;
  const upd = patch => setForm(f => ({ ...f, ...patch }));
  const save = () => {
    dispatch({ type: 'UPD_COMP', id: form.id, data: form });
    onClose();
  };

  return (
    <>
      <window.Modal
        title={
          <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <window.IdBadge id={form.id} />
            <window.TypeChip type={form.type} />
          </span>
        }
        width={660}
        onClose={onClose}
        footer={
          <>
            <button className="btn btn-danger-ghost btn-sm" onClick={() => setConfirm(true)}>Delete</button>
            <div style={{ flex: 1 }} />
            <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary btn-sm" onClick={save}>Save</button>
          </>
        }
      >
        <div className="form-grid">
          <div className="form-full">
            <window.Field label={<span style={{display:'flex',alignItems:'center',gap:8,textTransform:'none',letterSpacing:0,fontSize:12,fontWeight:500}}>Description <span style={{color:'var(--tx-d)',fontWeight:400,fontSize:11}}>— auto-generated from script</span></span>}>
              <div style={{position:'relative'}}>
                <input className="fi" value={genLoading ? 'Generating…' : (form.description||'')} readOnly
                  placeholder="Paste a script below — description auto-generates on save"
                  style={{paddingRight:100, fontStyle: form.description?'normal':'italic', color: form.description?'var(--tx)':'var(--tx-d)'}}
                />
                <button onClick={() => regenDesc(form.script, form.type)} disabled={genLoading||!form.script}
                  style={{position:'absolute',right:6,top:'50%',transform:'translateY(-50%)',
                    background:'var(--sf3)',border:'1px solid var(--bd)',borderRadius:4,
                    padding:'2px 9px',fontSize:11,color:'var(--tx)',cursor:'pointer',
                    opacity:(!form.script||genLoading)?.4:1}}>
                  {genLoading ? '…' : '↻ Regenerate'}
                </button>
              </div>
            </window.Field>
          </div>
          <div className="form-full">
            <window.Field label="Script">
              <textarea className="fi" value={form.script} onChange={e => upd({ script: e.target.value })}
                onBlur={e => handleScriptBlur(e.target.value, form.type, form.description)}
                placeholder="Paste full script here — description auto-generates when you leave this field…"
                style={{minHeight:260, lineHeight:1.6}} autoFocus />
            </window.Field>
          </div>
          <window.Field label="Status">
            <select className="fi" value={form.status} onChange={e => upd({ status: e.target.value })}>
              {COMP_STATUSES.map(s => <option key={s}>{s}</option>)}
            </select>
          </window.Field>
          <window.Field label="Editing Status">
            <select className="fi" value={form.editingStatus} onChange={e => upd({ editingStatus: e.target.value })}>
              {EDIT_STATUSES.map(s => <option key={s}>{s}</option>)}
            </select>
          </window.Field>
          <div className="form-full">
            <window.Field label="Video Link">
              <input className="fi" value={form.videoLink} onChange={e => upd({ videoLink: e.target.value })} placeholder="https://…" />
            </window.Field>
          </div>
          <div className="form-full">
            <window.Field label="Notes">
              <textarea className="fi" value={form.notes} onChange={e => upd({ notes: e.target.value })} placeholder="Internal notes…" />
            </window.Field>
          </div>
          <div style={{ color: '#3a3a58', fontSize: 11 }}>
            Created: {new Date(form.createdAt).toLocaleDateString()}
          </div>
        </div>
      </window.Modal>
      {confirm && (
        <window.ConfirmModal
          message={`Delete ${form.id} — "${form.description || 'this component'}"? This cannot be undone.`}
          onConfirm={() => { dispatch({ type: 'DEL_COMP', id: form.id }); setConfirm(false); onClose(); }}
          onCancel={() => setConfirm(false)}
        />
      )}
    </>
  );
}

function AddComponentModal({ compType, onClose }) {
  const { state, dispatch } = useContext(window.AppCtx);
  const [form, setForm] = useState({ description: '', status: 'Testing', editingStatus: 'Not Started', script: '', videoLink: '', notes: '' });
  const [genLoading, setGenLoading] = useState(false);
  const upd = patch => setForm(f => ({ ...f, ...patch }));

  const handleScriptBlur = useCallback(async (script) => {
    if (!script?.trim() || form.description) return;
    setGenLoading(true);
    const desc = await generateDescription(script, compType);
    if (desc) setForm(f => ({ ...f, description: desc }));
    setGenLoading(false);
  }, [form.description, compType]);

  const save = () => {
    dispatch({ type: 'ADD_COMP', compType, data: form });
    onClose();
  };

  return (
    <window.Modal
      title={<span>New <window.TypeChip type={compType} /></span>}
      width={600}
      onClose={onClose}
      footer={
        <>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={save}>Add {window.TYPE_STYLES[compType]?.label}</button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <window.Field label="Script">
          <textarea className="fi" value={form.script} onChange={e => upd({ script: e.target.value })}
            onBlur={e => handleScriptBlur(e.target.value)}
            placeholder={`Paste your ${compType} script here \u2014 description auto-generates when you click away\u2026`}
            style={{ minHeight: 200, lineHeight: 1.6 }} autoFocus />
        </window.Field>
        <window.Field label={<span style={{display:'flex',alignItems:'center',gap:8}}>Description <span style={{color:'var(--tx-d)',fontWeight:400,fontSize:11}}>\u2014 auto-generated</span></span>}>
          <div style={{ position: 'relative' }}>
            <input className="fi" value={genLoading ? 'Generating\u2026' : (form.description || '')} readOnly
              placeholder="Auto-generates from script above"
              style={{ paddingRight: 100, fontStyle: form.description ? 'normal' : 'italic', color: form.description ? 'var(--tx)' : 'var(--tx-d)' }}
            />
            <button onClick={() => { setGenLoading(true); generateDescription(form.script, compType).then(d => { if(d) upd({description:d}); setGenLoading(false); }); }}
              disabled={genLoading || !form.script}
              style={{ position:'absolute',right:6,top:'50%',transform:'translateY(-50%)',
                background:'var(--sf3)',border:'1px solid var(--bd)',borderRadius:4,
                padding:'2px 9px',fontSize:11,color:'var(--tx)',cursor:'pointer',
                opacity:(!form.script||genLoading)?.4:1 }}>
              {genLoading ? '\u2026' : '\u21bb Generate'}
            </button>
          </div>
        </window.Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <window.Field label="Status">
            <select className="fi" value={form.status} onChange={e => upd({ status: e.target.value })}>
              {COMP_STATUSES.map(s => <option key={s}>{s}</option>)}
            </select>
          </window.Field>
          <window.Field label="Editing Status">
            <select className="fi" value={form.editingStatus} onChange={e => upd({ editingStatus: e.target.value })}>
              {EDIT_STATUSES.map(s => <option key={s}>{s}</option>)}
            </select>
          </window.Field>
        </div>
        <window.Field label="Video Link">
          <input className="fi" value={form.videoLink} onChange={e => upd({ videoLink: e.target.value })} placeholder="https://\u2026" />
        </window.Field>
      </div>
    </window.Modal>
  );
}

function ComboDetailModal({ itemId, onClose, onOpenComponent }) {
  const { state, dispatch } = useContext(window.AppCtx);
  const wsId = state.activeWorkspaceId;
  const orig = state.combos.find(c => c.id === itemId && c.workspaceId === wsId);
  const [form, setForm] = useState(orig ? { ...orig } : null);
  const [confirm, setConfirm] = useState(false);

  const compsInWs = state.components.filter(c => c.workspaceId === wsId);
  const hooks = compsInWs.filter(c => c.type === 'hook');
  const leads = compsInWs.filter(c => c.type === 'lead');
  const bodies = compsInWs.filter(c => c.type === 'body');

  useEffect(() => {
    const c = state.combos.find(c => c.id === itemId && c.workspaceId === wsId);
    if (c) setForm({ ...c });
  }, [itemId, state.combos]);

  if (!form) return null;
  const upd = patch => setForm(f => ({ ...f, ...patch }));
  const save = () => {
    dispatch({ type: 'UPD_COMBO', id: form.id, data: form });
    onClose();
  };
  const refLink = (id, comps) => {
    const c = comps.find(x => x.id === id);
    if (!c) return null;
    return (
      <span
        style={{ fontFamily: 'var(--mono)', fontSize: 11, color: '#9090d4', textDecoration: 'underline', cursor: 'pointer', marginLeft: 6 }}
        onClick={e => { e.stopPropagation(); onOpenComponent && onOpenComponent(id); }}
      >{id}: {c.description?.slice(0, 40)}{c.description?.length > 40 ? '…' : ''}</span>
    );
  };

  return (
    <>
      <window.Modal
        title={<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><window.IdBadge id={form.id} /> Combo</span>}
        width={660}
        onClose={onClose}
        footer={
          <>
            <button className="btn btn-danger-ghost btn-sm" onClick={() => setConfirm(true)}>Delete</button>
            <div style={{ flex: 1 }} />
            <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary btn-sm" onClick={save}>Save</button>
          </>
        }
      >
        <div className="form-grid">
          <div className="form-full">
            <window.Field label="Name">
              <input className="fi" value={form.name} onChange={e => upd({ name: e.target.value })} />
            </window.Field>
          </div>
          <window.Field label="Status">
            <select className="fi" value={form.status} onChange={e => upd({ status: e.target.value })}>
              {COMBO_STATUSES.map(s => <option key={s}>{s}</option>)}
            </select>
          </window.Field>
          <window.Field label="Launch Date">
            <input className="fi" type="date" value={form.launchDate} onChange={e => upd({ launchDate: e.target.value })} />
          </window.Field>
          <window.Field label={<span>Hook (required) {form.hookId && refLink(form.hookId, hooks)}</span>}>
            <select className="fi" value={form.hookId} onChange={e => upd({ hookId: e.target.value })}>
              <option value="">— select hook —</option>
              {hooks.map(h => <option key={h.id} value={h.id}>{h.id}: {h.description}</option>)}
            </select>
          </window.Field>
          <window.Field label={<span>Lead (optional) {form.leadId && refLink(form.leadId, leads)}</span>}>
            <select className="fi" value={form.leadId} onChange={e => upd({ leadId: e.target.value })}>
              <option value="">— no lead —</option>
              {leads.map(l => <option key={l.id} value={l.id}>{l.id}: {l.description}</option>)}
            </select>
          </window.Field>
          <window.Field label={<span>Body (required) {form.bodyId && refLink(form.bodyId, bodies)}</span>}>
            <select className="fi" value={form.bodyId} onChange={e => upd({ bodyId: e.target.value })}>
              <option value="">— select body —</option>
              {bodies.map(b => <option key={b.id} value={b.id}>{b.id}: {b.description}</option>)}
            </select>
          </window.Field>
          <div className="form-full">
            <window.Field label="Post ID / Ads Manager Link">
              <input className="fi" value={form.postId} onChange={e => upd({ postId: e.target.value })} placeholder="optional…" />
            </window.Field>
          </div>
          <div className="form-full">
            <window.Field label="Notes">
              <textarea className="fi" value={form.notes} onChange={e => upd({ notes: e.target.value })} placeholder="Internal notes…" />
            </window.Field>
          </div>
          <div style={{ color: '#3a3a58', fontSize: 11 }}>
            Created: {new Date(form.createdAt).toLocaleDateString()}
          </div>
        </div>
      </window.Modal>
      {confirm && (
        <window.ConfirmModal
          message={`Delete combo ${form.id} — "${form.name}"? This cannot be undone.`}
          onConfirm={() => { dispatch({ type: 'DEL_COMBO', id: form.id }); setConfirm(false); onClose(); }}
          onCancel={() => setConfirm(false)}
        />
      )}
    </>
  );
}

function AddComboModal({ onClose, initialHookId = '', initialLeadId = '', initialBodyId = '' }) {
  const { state, dispatch } = useContext(window.AppCtx);
  const wsId = state.activeWorkspaceId;
  const comps = state.components.filter(c => c.workspaceId === wsId);
  const hooks = comps.filter(c => c.type === 'hook');
  const leads = comps.filter(c => c.type === 'lead');
  const bodies = comps.filter(c => c.type === 'body');
  const [form, setForm] = useState({
    hookId: initialHookId, leadId: initialLeadId, bodyId: initialBodyId, status: 'Draft', name: '', launchDate: '', postId: '', notes: ''
  });
  const upd = patch => setForm(f => ({ ...f, ...patch }));
  const autoName = () => [form.hookId, form.leadId, form.bodyId].filter(Boolean).join(' + ') || '';
  const save = () => {
    if (!form.hookId || !form.bodyId) return;
    const name = form.name.trim() || autoName();
    dispatch({ type: 'ADD_COMBO', data: { ...form, name } });
    onClose();
  };
  return (
    <window.Modal
      title="New Combo"
      width={560}
      onClose={onClose}
      footer={
        <>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={save} disabled={!form.hookId || !form.bodyId}>Add Combo</button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <window.Field label="Hook (required)">
          <select className="fi" value={form.hookId} onChange={e => upd({ hookId: e.target.value })} autoFocus>
            <option value="">— select hook —</option>
            {hooks.map(h => <option key={h.id} value={h.id}>{h.id}: {h.description}</option>)}
          </select>
        </window.Field>
        <window.Field label="Lead (optional)">
          <select className="fi" value={form.leadId} onChange={e => upd({ leadId: e.target.value })}>
            <option value="">— no lead —</option>
            {leads.map(l => <option key={l.id} value={l.id}>{l.id}: {l.description}</option>)}
          </select>
        </window.Field>
        <window.Field label="Body (required)">
          <select className="fi" value={form.bodyId} onChange={e => upd({ bodyId: e.target.value })}>
            <option value="">— select body —</option>
            {bodies.map(b => <option key={b.id} value={b.id}>{b.id}: {b.description}</option>)}
          </select>
        </window.Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <window.Field label="Starting Status">
            <select className="fi" value={form.status} onChange={e => upd({ status: e.target.value })}>
              {COMBO_STATUSES.map(s => <option key={s}>{s}</option>)}
            </select>
          </window.Field>
          <window.Field label="Name (auto if blank)">
            <input className="fi" value={form.name} onChange={e => upd({ name: e.target.value })} placeholder={autoName() || 'e.g. H1 + B3'} />
          </window.Field>
        </div>
      </div>
    </window.Modal>
  );
}

Object.assign(window, { ComponentDetailModal, AddComponentModal, ComboDetailModal, AddComboModal });
