// Author-facing screen for reviewing the agent-drafted marketplace listing
// and publishing it to the consumer marketplace. Reached via #/publish/:id.
// Only the workapp's owner can use it (server enforces via session userId).
(function () {
  const { useState, useEffect } = React;

  // Must match EVIDENCE_SOURCE_TYPES in server/lib/workapp-public-spec.ts.
  // If the server adds a type, mirror it here so the dropdown stays accurate.
  const EVIDENCE_SOURCE_TYPES = [
    'Buyer input', 'Page data', 'External tool',
    'External research', 'Customer signal', 'Expert method',
  ];

  function PublishContentScreen({ workappId, token }) {
    const [state, setState] = useState({ kind: 'loading' });

    useEffect(function () {
      if (!token) {
        setState({ kind: 'load-error', message: 'This page is only reachable from the builder agent. Ask the agent to "publish as content" and use the link it returns.' });
        return;
      }
      let cancelled = false;
      window.AppData.getMarketplaceDraft(workappId, token)
        .then(function (d) {
          if (cancelled) return;
          setState({ kind: 'editing', data: d });
        })
        .catch(function (err) {
          if (cancelled) return;
          if (err && err.status === 401) { window.AppData.redirectToLogin(); return; }
          setState({ kind: 'load-error', message: String(err.message || err) });
        });
      return function () { cancelled = true; };
    }, [workappId, token]);

    if (state.kind === 'loading') {
      return <div className="wrap" style={{padding: 40}}>Loading workapp…</div>;
    }
    if (state.kind === 'load-error') {
      return (
        <div className="wrap" style={{paddingTop: 80}}>
          <h1 className="serif">Couldn't load this workapp.</h1>
          <p style={{color: 'var(--muted)'}}>{state.message}</p>
        </div>
      );
    }
    return <PublishEditor workappId={workappId} token={token} initial={state.data} />;
  }

  function PublishEditor({ workappId, token, initial }) {
    const [draft, setDraft] = useState(initial.draft || makeEmptyDraft(initial.manifest));
    const [missing, setMissing] = useState(initial.missing || []);
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState(null);
    const [published, setPublished] = useState(false);

    function save() {
      setBusy(true); setError(null);
      window.AppData.saveMarketplaceDraft(workappId, draft, token)
        .then(function (r) { setMissing(r.missing || []); })
        .catch(function (e) { setError('Could not save: ' + (e.message || e)); })
        .finally(function () { setBusy(false); });
    }

    function regenerate() {
      if (!confirm('Replace the current draft with a fresh AI-generated one?')) return;
      setBusy(true); setError(null);
      window.AppData.regenerateMarketplaceDraft(workappId, token)
        .then(function (r) { setDraft(r.draft); setMissing(r.missing || []); })
        .catch(function (e) { setError('Regenerate failed: ' + (e.message || e)); })
        .finally(function () { setBusy(false); });
    }

    function publish() {
      setBusy(true); setError(null);
      window.AppData.saveMarketplaceDraft(workappId, draft, token)
        .then(function () { return window.AppData.publishMarketplace(workappId, token); })
        .then(function () { setPublished(true); })
        .catch(function (e) { setError('Publish failed: ' + (e.message || e)); })
        .finally(function () { setBusy(false); });
    }

    if (published) {
      return (
        <div className="wrap" style={{paddingTop: 80, maxWidth: 640}}>
          <h1 className="serif">Live on the marketplace.</h1>
          <p>Anyone with the link to your workapp can now run it.</p>
          <p style={{marginTop: 24}}>
            <a className="btn btn-primary" href="#/workapps">Open the marketplace →</a>
          </p>
        </div>
      );
    }

    return (
      <div className="wrap" style={{paddingTop: 56, maxWidth: 880}} data-screen-label="Publish as Content">
        <div className="section-label">Publish</div>
        <h1 className="serif" style={{fontSize: 40, margin: '8px 0 16px'}}>
          Review and publish: <em>{initial.manifest.name || 'this workapp'}</em>
        </h1>
        <p style={{color: 'var(--muted)', maxWidth: 600}}>
          An agent drafted the marketplace listing from your build session. Edit anything below, fill any missing
          fields, then click <b>Publish to Marketplace</b>. Once you publish, this workapp shows up in the consumer
          directory and anyone can run it.
        </p>

        {missing.length > 0 && (
          <div style={{marginTop: 24, padding: 16, background: 'color-mix(in srgb, var(--warn) 12%, transparent)', borderRadius: 'var(--r-md)'}}>
            <b>Please fill these before publishing:</b>
            <ul style={{margin: '8px 0 0 16px'}}>
              {missing.map(function (m) { return <li key={m}><code>{m}</code></li>; })}
            </ul>
          </div>
        )}

        {error && (
          <div style={{marginTop: 16, padding: 16, background: 'color-mix(in srgb, var(--bad) 12%, transparent)', borderRadius: 'var(--r-md)', color: 'var(--bad)'}}>
            {error}
          </div>
        )}

        <div style={{display: 'flex', gap: 8, margin: '24px 0', flexWrap: 'wrap'}}>
          <button className="btn btn-ghost" type="button" onClick={regenerate} disabled={busy}>⟳ Regenerate with AI</button>
          <button className="btn btn-ghost" type="button" onClick={save} disabled={busy}>Save draft</button>
          <button className="btn btn-primary" type="button" onClick={publish} disabled={busy || missing.length > 0}>
            {busy ? 'Working…' : 'Publish to Marketplace →'}
          </button>
        </div>

        <DraftEditor draft={draft} onChange={setDraft} />
      </div>
    );
  }

  function makeEmptyDraft(manifest) {
    return {
      expert: { name: '', title: '', bioShort: '', proofLine: '', tags: [] },
      sourcePost: { title: '', url: '' },
      identity: { title: manifest.name || '', subtitle: '', defaultAudience: '' },
      essay: { heading: '', bodyParagraphs: [''] },
      methodology: { methodologySteps: [], methodSummary: [], limitationsNote: '' },
      evidenceSources: [],
    };
  }

  function DraftEditor({ draft, onChange }) {
    function set(path, value) {
      const next = JSON.parse(JSON.stringify(draft || {}));
      const parts = path.split('.');
      let cur = next;
      for (let i = 0; i < parts.length - 1; i++) {
        if (cur[parts[i]] == null || typeof cur[parts[i]] !== 'object') cur[parts[i]] = {};
        cur = cur[parts[i]];
      }
      cur[parts[parts.length - 1]] = value;
      onChange(next);
    }

    const e = (draft && draft.expert) || {};
    const id = (draft && draft.identity) || {};
    const sp = (draft && draft.sourcePost) || {};
    const es = (draft && draft.essay) || {};
    const me = (draft && draft.methodology) || {};
    const sources = (draft && draft.evidenceSources) || [];

    return (
      <div style={{display: 'grid', gap: 32}}>
        <Section title="Expert">
          <Field label="Full name" value={e.name || ''} onChange={v => set('expert.name', v)} />
          <Field label="Role / title" value={e.title || ''} onChange={v => set('expert.title', v)} />
          <Field label="Photo URL (https://…)" value={e.photoUrl || ''} onChange={v => set('expert.photoUrl', v)} />
          <Field label="One-sentence bio (≤200 chars)" value={e.bioShort || ''} onChange={v => set('expert.bioShort', v)} />
          <FieldArea label="Full bio (2–4 sentences)" value={e.bioLong || ''} onChange={v => set('expert.bioLong', v)} />
          <Field label="Proof line (credentials)" value={e.proofLine || ''} onChange={v => set('expert.proofLine', v)} />
          <Field label="Tags (comma-separated)" value={(e.tags || []).join(', ')} onChange={v => set('expert.tags', v.split(',').map(s => s.trim()).filter(Boolean))} />
          <Field label="LinkedIn URL" value={e.linkedinUrl || ''} onChange={v => set('expert.linkedinUrl', v)} />
          <Field label="Website URL" value={e.websiteUrl || ''} onChange={v => set('expert.websiteUrl', v)} />
        </Section>

        <Section title="Source post (optional)">
          <Field label="Title" value={sp.title || ''} onChange={v => set('sourcePost.title', v)} />
          <Field label="URL" value={sp.url || ''} onChange={v => set('sourcePost.url', v)} />
        </Section>

        <Section title="Identity">
          <Field label="Headline (use *italic* for emphasis)" value={id.title || ''} onChange={v => set('identity.title', v)} />
          <Field label="Subtitle" value={id.subtitle || ''} onChange={v => set('identity.subtitle', v)} />
          <Field label="Default audience" value={id.defaultAudience || ''} onChange={v => set('identity.defaultAudience', v)} />
        </Section>

        <Section title="Essay">
          <Field label="Heading" value={es.heading || ''} onChange={v => set('essay.heading', v)} />
          <FieldArea label="Body paragraphs (blank line between)" value={(es.bodyParagraphs || []).join('\n\n')} onChange={v => set('essay.bodyParagraphs', v.split(/\n\n+/).map(s => s.trim()).filter(Boolean))} />
          <Field label="Pull quote" value={es.pullQuote || ''} onChange={v => set('essay.pullQuote', v)} />
        </Section>

        <Section title="Methodology — 5 steps">
          {Array.from({length: 5}, (_, i) => {
            const s = (me.methodologySteps || [])[i] || {};
            return (
              <div key={i} style={{display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 12, marginBottom: 8}}>
                <Field label={`Step ${i+1} title`} value={s.title || ''} onChange={v => {
                  const arr = [...(me.methodologySteps || [])];
                  arr[i] = { ...(arr[i] || {}), title: v };
                  set('methodology.methodologySteps', arr);
                }} />
                <Field label={`Step ${i+1} description`} value={s.description || ''} onChange={v => {
                  const arr = [...(me.methodologySteps || [])];
                  arr[i] = { ...(arr[i] || {}), description: v };
                  set('methodology.methodologySteps', arr);
                }} />
              </div>
            );
          })}
          <Field label="Limitations note" value={me.limitationsNote || ''} onChange={v => set('methodology.limitationsNote', v)} />
        </Section>

        <Section title="Method summary — 4 principles">
          {Array.from({length: 4}, (_, i) => {
            const s = (me.methodSummary || [])[i] || {};
            return (
              <div key={i} style={{display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 12, marginBottom: 8}}>
                <Field label={`Principle ${i+1} heading`} value={s.heading || ''} onChange={v => {
                  const arr = [...(me.methodSummary || [])];
                  arr[i] = { ...(arr[i] || {}), heading: v };
                  set('methodology.methodSummary', arr);
                }} />
                <Field label={`Principle ${i+1} body`} value={s.body || ''} onChange={v => {
                  const arr = [...(me.methodSummary || [])];
                  arr[i] = { ...(arr[i] || {}), body: v };
                  set('methodology.methodSummary', arr);
                }} />
              </div>
            );
          })}
        </Section>

        <Section title="Evidence sources">
          {sources.map((src, i) => (
            <div key={i} style={{display: 'grid', gridTemplateColumns: '1fr 1fr 2fr', gap: 12, marginBottom: 8}}>
              <Field label="Name" value={src.name || ''} onChange={v => {
                const arr = [...sources]; arr[i] = { ...arr[i], name: v }; set('evidenceSources', arr);
              }} />
              <SelectField label="Type" value={src.type || 'Page data'} options={EVIDENCE_SOURCE_TYPES} onChange={v => {
                const arr = [...sources]; arr[i] = { ...arr[i], type: v }; set('evidenceSources', arr);
              }} />
              <Field label="Note" value={src.note || ''} onChange={v => {
                const arr = [...sources]; arr[i] = { ...arr[i], note: v }; set('evidenceSources', arr);
              }} />
            </div>
          ))}
          <button className="btn btn-ghost btn-sm" type="button" onClick={() => set('evidenceSources', [...sources, { name: '', type: 'Page data', note: '' }])}>
            + Add evidence source
          </button>
        </Section>
      </div>
    );
  }

  function Section({ title, children }) {
    return (
      <section>
        <h2 className="serif" style={{margin: '0 0 12px', fontSize: 20}}>{title}</h2>
        <div style={{display: 'grid', gap: 12, padding: 16, border: '1px solid var(--hair)', borderRadius: 'var(--r-md)'}}>
          {children}
        </div>
      </section>
    );
  }

  function Field({ label, value, onChange }) {
    return (
      <div className="field">
        <label className="field-label">{label}</label>
        <input className="input" value={value} onChange={e => onChange(e.target.value)} />
      </div>
    );
  }

  function SelectField({ label, value, options, onChange }) {
    return (
      <div className="field">
        <label className="field-label">{label}</label>
        <select className="input" value={value} onChange={e => onChange(e.target.value)}>
          {options.map(opt => <option key={opt} value={opt}>{opt}</option>)}
        </select>
      </div>
    );
  }

  function FieldArea({ label, value, onChange }) {
    return (
      <div className="field">
        <label className="field-label">{label}</label>
        <textarea className="textarea" rows={4} value={value} onChange={e => onChange(e.target.value)} />
      </div>
    );
  }

  window.PublishContentScreen = PublishContentScreen;
})();
