/* Calibrated Ascension HQ — intake, projects, client onboarding. Exports to window. */
const { useState: useStateI, useRef: useRefI, useEffect: useEffectI } = React;

const HQ = window.HQ_DATA;
const agentByIdI = (id) => HQ.AGENTS.find((a) => a.id === id) || HQ.AGENTS[0];

/* ---------- Goal parser: turns a spoken/typed goal into a project ---------- */
function parseGoal(text, client) {
  const lower = text.toLowerCase();
  const has = (...ws) => ws.some((w) => lower.includes(w));
  const steps = [];
  const deliverables = [];
  const tags = [];
  const push = (agentId, label) => steps.push({ agentId, label });

  if (has("web", "website", "site", "funnel", "landing", "page", "design")) {
    tags.push("web");
    push("margo", "Define the page goal + offer");
    push("cole", "Build the page / funnel in GoHighLevel");
    push("juno", "Write the copy + source assets");
  }
  if (has("email", "sequence", "newsletter", "broadcast")) {
    tags.push("email");
    push("cole", "Set up the email in GoHighLevel");
    deliverables.push({
      id: "d" + Math.random().toString(36).slice(2, 7), type: "email",
      title: "Email to " + client.name, to: client.contact,
      subject: "Quick thing we need from you",
      body: `Hi ${client.name} team — we're moving on “${text.trim()}”. To keep it moving, could you confirm the details and anything you'd like included? Reply here and we'll turn it around fast.`,
    });
  }
  if (has("form", "intake", "questionnaire", "survey", "onboard")) {
    tags.push("form");
    push("cole", "Build the form in GoHighLevel");
    deliverables.push({
      id: "d" + Math.random().toString(36).slice(2, 7), type: "form",
      title: "Intake form for " + client.name, to: client.contact,
      fields: ["Primary goal for this project", "Brand assets (logo, photos)", "Key dates / deadline", "Anything we must include", "Who approves the final?"],
    });
  }
  if (has("doc", "document", "proposal", "contract", "scope", "sow", "agreement")) {
    tags.push("doc");
    deliverables.push({
      id: "d" + Math.random().toString(36).slice(2, 7), type: "doc",
      title: "Document for " + client.name, to: client.contact,
      body: `Scope for “${text.trim()}”.\n\n1. Objective\n2. Deliverables\n3. Timeline\n4. What we need from you\n\nReview and reply “approved” to begin.`,
    });
  }
  if (has("blog", "content", "post", "article", "social", "reel", "video", "caption", "script")) {
    tags.push("content"); push("juno", "Draft content + repurpose into assets");
  }
  if (has("ad", "ads", "traffic", "campaign", "launch", "seo", "reach", "audience")) {
    tags.push("traffic"); push("ravi", "Plan traffic + creative");
  }
  if (has("offer", "pricing", "price", "upsell", "bump", "ladder", "package", "tier")) {
    tags.push("offers"); push("margo", "Model the offer + pricing");
  }
  if (has("call", "community", "replay", "workshop", "recalibration", "event")) {
    tags.push("community"); push("sage", "Prep + post in the community");
  }

  if (steps.length === 0 && deliverables.length === 0) {
    push("atlas", "Anubis routes this to the right specialist");
  }
  steps.unshift({ agentId: "atlas", label: "Plan, assign & track across the team" });

  const title = text.trim().replace(/\s+/g, " ").replace(/^[a-z]/, (c) => c.toUpperCase());
  const dCount = deliverables.length;
  const summary = `Anubis assigned ${steps.length} step${steps.length === 1 ? "" : "s"}` + (dCount ? ` · ${dCount} thing${dCount === 1 ? "" : "s"} to send ${client.name}` : "");
  return { id: "cap" + Date.now(), title: title.length > 90 ? title.slice(0, 88) + "…" : title, status: "fresh", pm: "atlas", updated: "just now", who: summary, steps, deliverables, fresh: true };
}

/* ---------- The intake box ---------- */
function OnMind({ client, onCapture }) {
  const [val, setVal] = useStateI("");
  const [live, setLive] = useStateI(false);
  const [dots, setDots] = useStateI("");
  const timer = useRefI(null);
  const dotTimer = useRefI(null);

  const examples = [
    "Design a new spring promo landing page and send the client an intake form for their brand assets",
    "Draft the launch email sequence, get my approval, then send the client the offer proposal doc",
    "Build the booking funnel, send an intake form, and schedule the next workshop replay post",
    "Write 4 SEO blog posts and send the client a content-approval doc before we publish",
  ];

  useEffectI(() => () => { clearTimeout(timer.current); clearInterval(dotTimer.current); }, []);

  function toggleMic() {
    if (live) { stopMic(); return; }
    setLive(true);
    let n = 0;
    dotTimer.current = setInterval(() => { n = (n + 1) % 4; setDots(".".repeat(n)); }, 350);
    const ex = examples[Math.floor(Math.random() * examples.length)];
    // Simulated Wispr-style dictation — types the captured phrase in, word by word.
    const words = ex.split(" ");
    let i = 0;
    timer.current = setInterval(() => {
      i++;
      setVal((ex.split(" ").slice(0, i).join(" ")));
      if (i >= words.length) { stopMic(); }
    }, 90);
  }
  function stopMic() {
    setLive(false); setDots("");
    clearInterval(dotTimer.current); clearInterval(timer.current);
  }
  function capture() {
    const t = val.trim();
    if (!t) return;
    stopMic();
    onCapture(parseGoal(t, client));
    setVal("");
  }

  return (
    <div className="intake">
      <div className="intake-k">On your mind · {client.name}</div>
      <h3>What's on your mind today?</h3>
      <textarea className="intake-ta" value={val}
        placeholder={`Unload it — a goal or task for ${client.name}. e.g. “design the promo page and send them an intake form”…`}
        onChange={(e) => setVal(e.target.value)}
        onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); capture(); } }} />
      <div className="intake-actions">
        <button className={`mic-btn ${live ? "live" : ""}`} onClick={toggleMic}>
          <span className="mic-dot"></span>{live ? `Listening${dots}` : "Wispr Flow"}
        </button>
        <span className="intake-hint">{live ? "tap to stop" : "talk to unload — voice to task"}</span>
        <button className="btn btn-primary intake-go" disabled={!val.trim()} onClick={capture}>{I.spark} Unload to Anubis</button>
      </div>
    </div>
  );
}

/* ---------- Project card ---------- */
const DELIV_ICON = { email: "mail", form: "form", doc: "doc" };
const HEALTH_LABEL = { "on-track": "On track", "at-risk": "At risk", "blocked": "Blocked" };

/* Onboarding checklist for a project — completion %, missing items, mark-received */
function OnboardingPanel({ tasks, onMark }) {
  if (!tasks || tasks.length === 0) return null;
  const done = tasks.filter((t) => t.status === "received" || t.status === "na").length;
  const total = tasks.length;
  const pct = total ? Math.round((done / total) * 100) : 0;
  const missing = tasks.filter((t) => t.status === "pending");
  return (
    <div className="onb">
      <div className="onb-h">
        <span className="onb-title">{I.check} Onboarding</span>
        <span className="onb-pct">{pct}%</span>
      </div>
      <div className="onb-bar"><span style={{ width: pct + "%" }}></span></div>
      <div className="onb-sub">{done} of {total} received{missing.length ? ` · ${missing.length} missing` : " · complete"}</div>
      <div className="onb-items">
        {tasks.map((t) => (
          <div key={t.id} className="onb-item" data-status={t.status} title={t.help || ""}>
            <span className="onb-box">{(t.status === "received" || t.status === "na") ? I.check : ""}</span>
            <span className="onb-label">{t.label}</span>
            {t.status === "pending" && t.blocks_progress && <span className="onb-tag blocks">blocks</span>}
            {t.status === "pending" && !t.blocks_progress && <span className="onb-tag">missing</span>}
            {t.status === "pending" && onMark && <button className="btn btn-ghost btn-sm onb-btn" onClick={() => onMark(t.id, t.approval_id)}>Mark received</button>}
          </div>
        ))}
      </div>
    </div>
  );
}

function ProjectCard({ project, status, sent, onSend, onStatus, agents, pm, onAssignPM, approvals, onResolveApproval, onboarding, onMarkOnboarding }) {
  const st = status || project.status || "active";
  const pmId = pm || project.pm || "atlas";
  const pmAgent = (agents || []).find((a) => a.id === pmId) || (agents || [])[0];
  return (
    <div className="card proj" data-status={st}>
      <div className="proj-h">
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="proj-title">{project.title}</div>
          <div className="proj-sub">{project.who}</div>
        </div>
        <select className={`proj-status-sel ${st}`} value={st} onChange={(e) => onStatus(project.id, e.target.value)} onClick={(e) => e.stopPropagation()}>
          <option value="active">Active</option>
          <option value="blocked">Blocked</option>
          <option value="done">Done</option>
        </select>
      </div>
      {(project.package || project.stage || project.health) && (
        <div className="proj-meta">
          {project.package && <span className="proj-badge pkg">{project.package}</span>}
          {project.stage && <span className="proj-badge stage">{project.stage}</span>}
          {project.health && <span className={`proj-health ${project.health}`}>{HEALTH_LABEL[project.health] || project.health}</span>}
        </div>
      )}
      {typeof project.completion === "number" && (
        <div className="proj-prog" title={`${project.completion}% complete`}>
          <div className="proj-prog-bar"><span style={{ width: project.completion + "%" }}></span></div>
          <span className="proj-prog-n">{project.completion}%</span>
        </div>
      )}
      <div className="proj-pm">
        {pmAgent && <Avatar agent={pmAgent} size="sm" />}
        <span className="proj-pm-lbl">PM</span>
        <select className="proj-pm-sel" value={pmId} onChange={(e) => onAssignPM && onAssignPM(project.id, e.target.value)} onClick={(e) => e.stopPropagation()}>
          {(agents || []).map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
        </select>
        <span className="proj-updated">updated {project.updated || "just now"}</span>
      </div>
      {project.agents && project.agents.length > 0 && (
        <div className="proj-agents">
          <span className="proj-agents-lbl">Team</span>
          {project.agents.map((id) => <Avatar key={id} agent={agentByIdI(id)} size="sm" />)}
        </div>
      )}
      {((project.waiting && project.waiting.length > 0) || project.bottleneck) && (
        <div className="proj-waiting">
          <div className="proj-waiting-h">{I.warn} {st === "blocked" ? "Blocked — waiting on" : "Current bottleneck"}</div>
          {project.waiting && project.waiting.length > 0 && (
            <div className="proj-waiting-items">
              {project.waiting.map((w, i) => <span key={i} className="proj-wait-chip">{w}</span>)}
            </div>
          )}
          {project.bottleneck && <div className="proj-bottleneck">{project.bottleneck}</div>}
        </div>
      )}
      <div className="proj-steps">
        {(project.steps || []).map((s, i) => {
          const a = agentByIdI(s.agentId);
          return (
            <div key={i} className="proj-step">
              <Avatar agent={a} size="sm" />
              <span>{s.label}</span>
            </div>
          );
        })}
      </div>
      {project.deliverables && project.deliverables.length > 0 && (
        <div className="proj-deliv">
          {project.deliverables.map((d) => {
            const isSent = sent.includes(d.id);
            return (
              <div key={d.id} className="deliv">
                <div className="deliv-ico">{I[DELIV_ICON[d.type]]}</div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div className="deliv-name">{d.title} <span style={{ color: "var(--ink-3)", fontWeight: 400, textTransform: "capitalize" }}>· {d.type}</span></div>
                  <div className="deliv-to">to {d.to}</div>
                </div>
                {isSent
                  ? <span className="deliv-sent">{I.check} Sent</span>
                  : <button className="btn btn-primary btn-sm deliv-act" onClick={() => onSend(d)}>{I.send} Send to client</button>}
              </div>
            );
          })}
        </div>
      )}
      <OnboardingPanel tasks={onboarding} onMark={onMarkOnboarding} />
      {approvals && approvals.length > 0 && (
        <div className="proj-approvals">
          <div className="proj-approvals-h">{I.check} Approvals · {approvals.filter((a) => a.status === "open" || a.status === "changes_requested").length} open</div>
          {approvals.map((a) => <ApprovalRow key={a.id} a={a} data={{ AGENTS: agents }} onResolve={onResolveApproval} />)}
        </div>
      )}
    </div>
  );
}

/* ---------- Output composer (email / form / doc) ---------- */
function OutputComposer({ deliverable, client, onClose, onSend }) {
  const d = deliverable;
  const [to, setTo] = useStateI(d.to);
  const [subject, setSubject] = useStateI(d.subject || "");
  const [body, setBody] = useStateI(d.body || "");
  const [fields, setFields] = useStateI((d.fields || []).join("\n"));
  const [via, setVia] = useStateI(d.type === "doc" ? "gdoc" : "email");
  const label = d.type === "email" ? "Email" : d.type === "form" ? "Form" : "Document";
  const viaOpts = [{ v: "email", l: "Email" }, { v: "gdoc", l: "Google Doc" }, { v: "drive", l: "Drive" }];

  return (
    <div className="ov" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-h">
          <div className="deliv-ico" style={{ width: 38, height: 38, background: "var(--accent-soft)", color: "var(--accent-ink)", borderColor: "var(--accent-line)" }}>{I[DELIV_ICON[d.type]]}</div>
          <div style={{ flex: 1 }}>
            <div className="sheet-title">{label} for {client.name}</div>
            <div className="sheet-sub">Review &amp; edit, then send straight to your client.</div>
          </div>
          <button className="x-btn" onClick={onClose}>{I.x}</button>
        </div>
        <div className="sheet-b">
          <div className="set-row" style={{ paddingTop: 0, marginBottom: 4 }}>
            <div><div className="set-name">Deliver via</div><div className="set-sub">{via === "gdoc" ? "Shared as a Google Doc the client can comment on" : via === "drive" ? "Dropped into your shared Drive folder" : "Sent as an email"}</div></div>
            <div className="seg">
              {viaOpts.map((o) => <button key={o.v} className="seg-opt" data-active={via === o.v} onClick={() => setVia(o.v)}>{o.l}</button>)}
            </div>
          </div>
          <div className="field">
            <label>To</label>
            <input value={to} onChange={(e) => setTo(e.target.value)} />
          </div>
          {d.type === "email" && (
            <React.Fragment>
              <div className="field"><label>Subject</label><input value={subject} onChange={(e) => setSubject(e.target.value)} /></div>
              <div className="field"><label>Message</label><textarea rows="7" value={body} onChange={(e) => setBody(e.target.value)} /></div>
            </React.Fragment>
          )}
          {d.type === "form" && (
            <div className="field">
              <label>Form fields (one per line)</label>
              <textarea rows="7" value={fields} onChange={(e) => setFields(e.target.value)} />
              <div className="intake-hint" style={{ marginTop: 7 }}>Sent as a hosted GoHighLevel form — the client fills it in and it lands back here.</div>
            </div>
          )}
          {d.type === "doc" && (
            <div className="field"><label>Document</label><textarea rows="9" value={body} onChange={(e) => setBody(e.target.value)} /></div>
          )}
          <div className="actions" style={{ marginTop: 4 }}>
            <button className="btn btn-primary" onClick={() => onSend(d.id, to, via)}>{I.send} {via === "email" ? "Approve & send" : via === "gdoc" ? "Approve & share doc" : "Approve & save to Drive"}</button>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Add client (onboarding) ---------- */
const CLIENT_COLORS = ["oklch(0.62 0.12 25)", "oklch(0.62 0.10 240)", "oklch(0.60 0.11 300)", "oklch(0.60 0.10 150)", "oklch(0.56 0.08 60)", "oklch(0.58 0.12 200)"];
function AddClientModal({ onClose, onAdd }) {
  const [name, setName] = useStateI("");
  const [contact, setContact] = useStateI("");
  const [loc, setLoc] = useStateI("");
  const [key, setKey] = useStateI("");
  const [connected, setConnected] = useStateI(false);
  const [drive, setDrive] = useStateI(false);
  const [devEnv, setDevEnv] = useStateI(false);

  function initials(n) {
    const parts = n.trim().split(/\s+/);
    return ((parts[0]?.[0] || "") + (parts[1]?.[0] || parts[0]?.[1] || "")).toUpperCase() || "CL";
  }
  function submit() {
    if (!name.trim()) return;
    const id = name.toLowerCase().replace(/[^a-z0-9]+/g, "").slice(0, 10) + Math.random().toString(36).slice(2, 4);
    onAdd({
      id, name: name.trim(), kind: "Client", initials: initials(name),
      color: CLIENT_COLORS[Math.floor(Math.random() * CLIENT_COLORS.length)],
      connected: connected && !!loc, contact: contact.trim() || "—", ghl: loc.trim(), pinned: false, drive, wantsEnv: devEnv,
    });
  }

  return (
    <div className="ov" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-h">
          <div className="deliv-ico" style={{ width: 38, height: 38, background: "var(--accent-soft)", color: "var(--accent-ink)", borderColor: "var(--accent-line)" }}>{I.plus}</div>
          <div style={{ flex: 1 }}>
            <div className="sheet-title">Onboard a client</div>
            <div className="sheet-sub">Connect their GoHighLevel so the team can run their account.</div>
          </div>
          <button className="x-btn" onClick={onClose}>{I.x}</button>
        </div>
        <div className="sheet-b">
          <div className="ghl-connect" data-on={connected && !!loc}>
            <div className="gc-ico">{I.plug}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>{connected && loc ? "GoHighLevel connected" : "Connect GoHighLevel"}</div>
              <div className="intake-hint">{connected && loc ? "Location authorized · ready to run workflows" : "Authorize the sub-account to sync contacts, funnels & forms"}</div>
            </div>
            <button className={`btn btn-sm ${connected && loc ? "btn-ghost" : "btn-primary"}`} onClick={() => setConnected((c) => !c)}>
              {connected && loc ? "Connected" : "Connect"}
            </button>
          </div>
          <div className="ghl-connect" data-on={drive} style={{ marginTop: -6 }}>
            <div className="gc-ico" style={{ background: "var(--blue-soft)", color: "var(--blue)" }}>{I.drive}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>{drive ? "Google Drive connected" : "Connect Google Drive"}</div>
              <div className="intake-hint">{drive ? "Docs, forms & files shared straight to the client" : "Use Drive & Docs as a shared channel with this client"}</div>
            </div>
            <button className={`btn btn-sm ${drive ? "btn-ghost" : "btn-primary"}`} onClick={() => setDrive((d) => !d)}>
              {drive ? "Connected" : "Connect"}
            </button>
          </div>
          <div className="ghl-connect" data-on={devEnv} style={{ marginTop: -6 }}>
            <div className="gc-ico" style={{ background: "oklch(0.22 0.01 260)", color: "#fff" }}>{I.gitbranch}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Developer environment</div>
              <div className="intake-hint">{devEnv ? "We'll set up GitHub + Vercel + plugins right after" : "Connect GitHub, Vercel & plugins so agents can ship"}</div>
            </div>
            <button className={`btn btn-sm ${devEnv ? "btn-ghost" : "btn-primary"}`} onClick={() => setDevEnv((d) => !d)}>
              {devEnv ? "Queued" : "Set up"}
            </button>
          </div>
          <div className="field"><label>Client / business name</label><input value={name} placeholder="e.g. Harbor & Co" onChange={(e) => setName(e.target.value)} /></div>
          <div className="field"><label>Primary contact email</label><input value={contact} placeholder="admin@client.com" onChange={(e) => setContact(e.target.value)} /></div>
          <div className="field-row">
            <div className="field"><label>GHL Location ID</label><input value={loc} placeholder="loc_xxxxxx" onChange={(e) => setLoc(e.target.value)} /></div>
            <div className="field"><label>API key / Client ID</label><input value={key} placeholder="••••••••" onChange={(e) => setKey(e.target.value)} /></div>
          </div>
          <div className="actions" style={{ marginTop: 4 }}>
            <button className="btn btn-primary" disabled={!name.trim()} onClick={submit}>{I.check} Add client</button>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- All clients list ---------- */
function AllClientsModal({ clients, current, onSelect, onClose, onAdd, onRetire, onReactivate }) {
  const agency = clients.find((c) => c.agency);
  const list = clients.filter((c) => !c.agency);
  function row(c, isAgency) {
    return (
      <div key={c.id} className="client-row" data-active={current === c.id} data-dormant={c.dormant ? "1" : null}>
        <button className="cr-main" onClick={() => onSelect(c.id)}>
          <span className="client-badge" style={{ background: c.color, width: 34, height: 34 }}>{c.initials}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="cr-name">{c.name}</div>
            <div className="cr-meta"><span className={`conn-dot ${c.dormant ? "off" : c.connected ? "on" : "off"}`}></span>{isAgency ? "Your agency" : c.dormant ? "Dormant · agents asleep" : c.connected ? `GHL ${c.ghl}` : "GoHighLevel not connected"}</div>
          </div>
        </button>
        {isAgency
          ? <span className="cr-tag on">connected</span>
          : c.dormant
            ? <button className="btn btn-ghost btn-sm" onClick={() => onReactivate(c.id)}>{I.spark} Reactivate</button>
            : <button className="btn btn-ghost btn-sm cr-retire" onClick={() => onRetire(c.id)}>{I.archive} Retire</button>}
      </div>
    );
  }
  return (
    <div className="ov" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-h">
          <div className="deliv-ico" style={{ width: 38, height: 38, background: "var(--accent-soft)", color: "var(--accent-ink)", borderColor: "var(--accent-line)" }}>{I.users}</div>
          <div style={{ flex: 1 }}>
            <div className="sheet-title">All accounts</div>
            <div className="sheet-sub">{list.length} client{list.length === 1 ? "" : "s"} · your agency</div>
          </div>
          <button className="x-btn" onClick={onClose}>{I.x}</button>
        </div>
        <div className="sheet-b">
          {agency && row(agency, true)}
          <div className="post-flabel" style={{ margin: "14px 0 8px" }}>Clients</div>
          {list.map((c) => row(c, false))}
          <button className="btn btn-ghost" style={{ marginTop: 8, width: "100%", justifyContent: "center" }} onClick={onAdd}>{I.plus} Onboard a client</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Fallback context for accounts without a rich brief ---------- */
function genContext(client) {
  const conn = client.connected;
  return {
    greeting: conn ? `${client.name} is connected. Capture a goal and the team gets to work.` : `${client.name} isn't connected yet — link their GoHighLevel to start running their account.`,
    metrics: {
      offers: { value: "—", label: "Pipeline", delta: "no data yet", up: true, sub: "" },
      automation: { value: conn ? "—" : "0", label: "Workflows", delta: conn ? "ready" : "connect GHL", up: conn, sub: "" },
      traffic: { value: "—", label: "CPL", delta: "no data yet", up: true, sub: "" },
    },
    decisions: [],
    tomorrow: {
      offers: ["Capture a goal above to plan offers"],
      automation: conn ? ["Set up the first workflow"] : ["Connect GoHighLevel"],
      traffic: ["Capture a goal to plan traffic"],
    },
    risks: [],
    projects: [],
  };
}

Object.assign(window, { parseGoal, OnMind, ProjectCard, OutputComposer, AddClientModal, AllClientsModal, genContext });
