/* AIWine CRM — founder AI tools: research brief, meeting intelligence,
   proposal generator. All call store.aiComplete (window.claude here; the
   /api/ai serverless proxy on the deployed site). */

const AI_VOICE = 'You are the sales analyst for AIWine — the AI-powered virtual cellar door for New Zealand & Australian wine, sold to wineries. AIWine lists a winery\u2019s wines, recommends them to consumers via an AI sommelier, and sells direct from the winery. New Zealand voice, concise, plain, no hype, no emoji.';

function wineryFacts(w) {
  const f = [];
  f.push('Winery: ' + w.name);
  if (w.region) f.push('Region: ' + w.region + ' (' + (w.country || 'NZ') + ')');
  if (w.website) f.push('Website: ' + w.website);
  if (w.ownership) f.push('Ownership: ' + w.ownership);
  if (w.sizeCategory) f.push('Size: ' + w.sizeCategory);
  if (w.annualProduction) f.push('Production: ' + w.annualProduction);
  if (w.hasCellarDoor != null) f.push('Cellar door: ' + (w.hasCellarDoor ? 'yes' : 'no'));
  if (w.hasWineClub != null) f.push('Wine club: ' + (w.hasWineClub ? 'yes' : 'no'));
  ['ecommercePlatform', 'crmUsed', 'websitePlatform', 'emailPlatform', 'bookingSystem', 'accountingSystem'].forEach((k) => { if (w[k]) f.push(k + ': ' + w[k]); });
  if (w.aiSentiment) f.push('AI sentiment: ' + w.aiSentiment);
  return f.join('\n');
}

/* ---------- research brief (writes w.aiSummary) ---------- */
function AIResearchButton({ w }) {
  const store = window.UI.useStore();
  const { toast, Ic } = window.UI;
  const [busy, setBusy] = React.useState(false);
  const run = async () => {
    setBusy(true);
    try {
      const prompt = wineryFacts(w) + '\n\nWrite a short sales research brief for AIWine\u2019s founder, in 4 tight parts:\n1. Snapshot — what this winery likely is (style, scale, audience).\n2. Likely digital setup — best-guess ecommerce/email/booking tools and gaps.\n3. Why AIWine fits — the 1-2 strongest hooks for THIS winery.\n4. Next best action — one concrete first move.\nUnder 180 words total. Plain prose with the four headings. Mark anything uncertain as a guess to verify.';
      const text = await store.aiComplete({ system: AI_VOICE, prompt, url: w.website ? (/^https?:/.test(w.website) ? w.website : 'https://' + w.website) : null, maxTokens: 700 });
      if (!text) throw new Error('No response');
      await store.update('wineries', w.id, { aiSummary: text });
      store.audit('Generated AI research brief for ' + w.name, 'winery');
      toast('Research brief saved');
    } catch (err) { toast(err.message); }
    setBusy(false);
  };
  return <button className="btn btn-ghost btn-sm" disabled={busy} onClick={run}><Ic name="sparkle" w={13} /> {busy ? 'Researching…' : (w.aiSummary ? 'Regenerate brief' : 'AI research brief')}</button>;
}

/* ---------- meeting intelligence ---------- */
function MeetingIntelModal({ w, onClose }) {
  const store = window.UI.useStore();
  const { toast, Field } = window.UI;
  const [notes, setNotes] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [out, setOut] = React.useState(null);

  const extract = async () => {
    if (!notes.trim()) { toast('Paste your meeting notes first'); return; }
    setBusy(true);
    try {
      const prompt = 'Winery: ' + w.name + '\n\nMeeting notes:\n"""\n' + notes.slice(0, 8000) + '\n"""\n\nExtract structured intelligence. Reply with ONLY valid JSON, no prose, in this exact shape:\n{"painPoints":[],"budget":"","decisionMakers":[],"competitors":[],"nextSteps":[],"risks":[],"summary":""}\nUse short strings. Empty arrays if nothing found.';
      const raw = await store.aiComplete({ system: AI_VOICE, prompt, maxTokens: 900 });
      let parsed = null;
      try { const m = raw.match(/\{[\s\S]*\}/); parsed = JSON.parse(m ? m[0] : raw); } catch (e) { parsed = null; }
      if (!parsed) { setOut({ raw }); } else { setOut(parsed); }
    } catch (err) { toast(err.message); }
    setBusy(false);
  };

  const save = async () => {
    const o = out || {};
    const lines = [];
    if (o.summary) lines.push(o.summary);
    const sec = (label, arr) => { if (arr && arr.length) lines.push(label + ': ' + arr.join('; ')); };
    sec('Pain points', o.painPoints); if (o.budget) lines.push('Budget: ' + o.budget);
    sec('Decision makers', o.decisionMakers); sec('Competitors', o.competitors);
    sec('Next steps', o.nextSteps); sec('Risks', o.risks);
    const body = 'Meeting (AI): ' + (lines.join(' \u00b7 ') || notes.slice(0, 300));
    await store.insert('notes', { wineryId: w.id, author: (store.user ? store.user.name : 'AI') + ' / meeting', at: new Date().toISOString(), body });
    store.audit('Logged AI meeting summary for ' + w.name, 'note');
    toast('Saved to timeline'); onClose();
  };

  const Chips = ({ label, arr }) => (arr && arr.length) ? (
    <div style={{ marginBottom: 10 }}>
      <div className="label" style={{ marginBottom: 5 }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{arr.map((x, i) => <span key={i} className="badge" style={{ background: 'var(--bone-alt)', color: 'var(--ink-soft)' }}>{x}</span>)}</div>
    </div>
  ) : null;

  return (
    <window.UI.Modal wide title={'Meeting intelligence · ' + w.name} sub="Paste notes — AI extracts the structure" onClose={onClose}
      foot={<React.Fragment>
        <button className="btn btn-ghost" onClick={onClose}>Close</button>
        {!out && <button className="btn btn-primary" disabled={busy} onClick={extract}>{busy ? 'Reading…' : 'Extract'}</button>}
        {out && <button className="btn btn-ghost" onClick={() => setOut(null)}>Re-do</button>}
        {out && <button className="btn btn-primary" onClick={save}>Save to timeline</button>}
      </React.Fragment>}>
      {!out && (
        <Field label="Meeting notes">
          <textarea className="input" rows="10" value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Paste raw notes from the call or visit — bullet points are fine." autoFocus style={{ fontSize: 13, lineHeight: 1.6 }} />
        </Field>
      )}
      {out && out.raw && <div style={{ whiteSpace: 'pre-wrap', fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.6 }}>{out.raw}</div>}
      {out && !out.raw && (
        <div>
          {out.summary && <p style={{ fontSize: 14, color: 'var(--ink)', marginBottom: 14, lineHeight: 1.6 }}>{out.summary}</p>}
          <Chips label="Pain points" arr={out.painPoints} />
          {out.budget && <div style={{ marginBottom: 10 }}><div className="label" style={{ marginBottom: 5 }}>Budget</div><span style={{ fontSize: 13 }}>{out.budget}</span></div>}
          <Chips label="Decision makers" arr={out.decisionMakers} />
          <Chips label="Competitors" arr={out.competitors} />
          <Chips label="Next steps" arr={out.nextSteps} />
          <Chips label="Risks" arr={out.risks} />
        </div>
      )}
    </window.UI.Modal>
  );
}

/* ---------- proposal generator ---------- */
function ProposalModal({ w, opp, onClose }) {
  const store = window.UI.useStore();
  const { toast } = window.UI;
  const [busy, setBusy] = React.useState(false);
  const [text, setText] = React.useState('');

  const gen = async () => {
    setBusy(true);
    try {
      const prompt = wineryFacts(w) + '\n'
        + (opp ? ('Deal: ' + (opp.title || '') + ' · stage ' + opp.stage + (opp.value ? ' · ~$' + opp.value + '/yr' : '') + '\n') : '')
        + (opp && opp.problems ? 'Known problems: ' + opp.problems + '\n' : '')
        + (opp && opp.solutions ? 'Intended solutions: ' + opp.solutions + '\n' : '')
        + '\nDraft a one-page AIWine proposal for this winery, with these headings:\nOverview · What we propose · Scope · Pricing (mark figures as indicative TBD — never invent firm prices) · Benefits · Expected outcomes · Next steps.\nWarm, plain, NZ voice. ~300 words. Address the winery by name.';
      const out = await store.aiComplete({ system: AI_VOICE, prompt, maxTokens: 1400 });
      setText(out);
    } catch (err) { toast(err.message); }
    setBusy(false);
  };
  React.useEffect(() => { gen(); }, []);

  const copy = () => { try { navigator.clipboard.writeText(text); toast('Copied'); } catch (e) {} };
  const saveNote = async () => {
    await store.insert('notes', { wineryId: w.id, author: (store.user ? store.user.name : 'AI') + ' / proposal', at: new Date().toISOString(), body: 'Proposal draft:\n' + text });
    store.audit('Generated proposal for ' + w.name, 'note'); toast('Saved to timeline'); onClose();
  };

  return (
    <window.UI.Modal wide title={'Proposal · ' + w.name} sub="AI draft — review before sending" onClose={onClose}
      foot={<React.Fragment>
        <button className="btn btn-ghost" style={{ marginRight: 'auto' }} disabled={busy} onClick={gen}>{busy ? 'Writing…' : 'Regenerate'}</button>
        <button className="btn btn-ghost" disabled={!text} onClick={copy}>Copy</button>
        <button className="btn btn-primary" disabled={!text} onClick={saveNote}>Save to timeline</button>
      </React.Fragment>}>
      {busy && !text ? <div style={{ padding: '30px 0', textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>Drafting the proposal…</div>
        : <textarea className="input" rows="18" value={text} onChange={(e) => setText(e.target.value)} style={{ fontSize: 13, lineHeight: 1.65 }} />}
      <div style={{ fontSize: 12, color: 'var(--brass)', marginTop: 8 }}>Always check pricing and claims before sending — this is a draft.</div>
    </window.UI.Modal>
  );
}

Object.assign(window, { AIResearchButton, MeetingIntelModal, ProposalModal, draftReply });

/* ---------- AI draft reply (for approval) to an inbound email ---------- */
async function draftReply(store, email, winery) {
  const ctx = winery ? ('Winery: ' + winery.name + (winery.region ? ' (' + winery.region + ')' : '') + '. ') : '';
  const prompt = ctx + 'A ' + (email.audience === 'consumer' ? 'consumer' : 'winery contact') + ' (' + (email.toName || email.toEmail) + ') sent this email:\n\n"""\nSubject: ' + (email.subject || '') + '\n' + (email.body || '').slice(0, 4000) + '\n"""\n\nDraft a warm, concise reply on behalf of AIWine. Answer their questions, move the relationship forward, suggest a clear next step. Plain NZ voice, no hype. Do NOT invent pricing or commitments — if pricing comes up, say terms are being finalised with founding wineries. Return only the reply body (no subject line, no signature placeholder beyond "Ngā mihi,").';
  const body = await store.aiComplete({ system: AI_VOICE, prompt, maxTokens: 700 });
  const subj = /^re:/i.test(email.subject || '') ? email.subject : ('Re: ' + (email.subject || 'your enquiry'));
  return { subject: subj, body };
}
