/* MatchPlan.ai — Post-call intelligence (MatchIQ style). */

const VERDICTS = {
  pursue:       { label: "Pursue", tone: "green", t: "t-green", icon: "TrendingUp" },
  nurture:      { label: "Nurture", tone: "gold", t: "t-gold", icon: "Sprout" },
  deprioritize: { label: "De-prioritize", tone: "red", t: "t-red", icon: "Archive" }
};
const DEAL_STAGES = ["Discovery", "Demo", "Proposal", "Closed Won", "Closed Lost"];

function PostCallPage({ id, path }) {
  const toast = useToast();
  const prep = MP.getPrep(id);
  const existing = MP.getPostCall(id);
  const [analysis, setAnalysis] = React.useState(existing || null);
  const [text, setText] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [drag, setDrag] = React.useState(false);
  const fileRef = React.useRef(null);
  const prospect = prep ? prep.prospect : "this call";

  const onFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => setText(String(e.target.result || ""));
    reader.readAsText(file);
  };
  const analyze = () => {
    if (!text.trim()) return;
    setLoading(true);
    setTimeout(() => { const pc = MP.savePostCall(id, text, prospect); setAnalysis(pc); setLoading(false); }, 1700);
  };

  return (
    <Shell path={path} width="mp-w-3xl">
      <PageHeader title={"Post-call analysis" + (prep ? " · " + prep.prospect : "")}
        eyebrow={<><Icon name="FileAudio" size={13} /> Post-call</>}
        subtitle="Drop in your transcript — we'll score it go or no-go, plan your follow-up call, and flag the roles to bring."
        back={prep ? { to: "/prepare/" + id, label: "Back to brief" } : { to: "/dashboard", label: "Back to home" }} />

      {!analysis && !loading && (
        <Card pad className="mp-fade">
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Field label="Paste your call transcript or notes">
              <Textarea rows={8} value={text} onChange={(e) => setText(e.target.value)}
                placeholder="Paste the transcript, or your scribbled notes — whatever you've got. We'll find the signal." />
            </Field>
            <div className={`mp-dropzone${drag ? " is-drag" : ""}`}
              onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
              onDragLeave={() => setDrag(false)}
              onDrop={(e) => { e.preventDefault(); setDrag(false); onFile(e.dataTransfer.files[0]); }}
              onClick={() => fileRef.current && fileRef.current.click()}>
              <Icon name="UploadCloud" size={24} />
              <span style={{ fontSize: "var(--fs-subtitle-2)", fontWeight: 700, color: "var(--fg-1)" }}>Drop a .txt or .vtt file</span>
              <span style={{ fontSize: "var(--fs-body-3)", color: "var(--fg-3)" }}>or click to browse</span>
              <input ref={fileRef} type="file" accept=".txt,.vtt,text/plain" style={{ display: "none" }} onChange={(e) => onFile(e.target.files[0])} />
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <Button size="lg" icon="AudioLines" disabled={!text.trim()} onClick={analyze}>Analyze the call</Button>
            </div>
          </div>
        </Card>
      )}

      {loading && (
        <Card pad className="mp-fade">
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 22, padding: "28px 0" }}>
            <Waveform />
            <p style={{ margin: 0, fontSize: "var(--fs-subtitle-1)", fontWeight: 700, color: "var(--fg-1)" }}>Listening to the conversation…</p>
          </div>
        </Card>
      )}

      {analysis && !loading && (
        <PostCallResult analysis={analysis} id={id} toast={toast} onReset={() => { setAnalysis(null); setText(""); }} />
      )}
    </Shell>
  );
}

function Waveform() {
  const bars = [0.3, 0.7, 0.45, 0.95, 0.6, 0.85, 0.35, 0.75, 0.5, 0.9, 0.4, 0.65, 0.55, 0.8];
  return (
    <div className="mp-waveform">
      {bars.map((b, i) => <span key={i} className="mp-wave-bar" style={{ height: (b * 100) + "%", animationDelay: (i * 0.07) + "s" }}></span>)}
    </div>
  );
}

function PostCallResult({ analysis, id, toast, onReset }) {
  const v = VERDICTS[analysis.verdict];
  const [steps, setSteps] = React.useState(analysis.steps);
  const [stage, setStage] = React.useState(analysis.dealStage);
  const toggle = (i) => setSteps(s => s.map((x, j) => j === i ? { ...x, done: !x.done } : x));
  const userName = (MP.get().user && MP.get().user.name) || "Jordan";

  return (
    <div className="mp-stack mp-fade">
      {/* verdict */}
      <div className={`mp-verdict ${v.t}`}>
        <span className="mp-verdict__icon" style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 52, height: 52, borderRadius: "var(--radius-lg)", background: "var(--bg-surface)", boxShadow: "var(--shadow-sm)", flexShrink: 0 }}>
          <Icon name={v.icon} size={26} />
        </span>
        <div>
          <div className="mp-verdict__eyebrow">The verdict</div>
          <h2 className="mp-verdict__h">{v.label}</h2>
          <p style={{ margin: "10px 0 0", fontSize: "var(--fs-body-1)", color: "var(--fg-1)", lineHeight: 1.55, maxWidth: "60ch" }}>{analysis.why}</p>
        </div>
      </div>

      {/* key moments */}
      <Section icon="ListChecks" title="Key moments" subtitle="The lines that mattered.">
        <ul className="mp-moments">
          {analysis.moments.map((m, i) => (
            <li key={i}><span className="mp-moments__t">{m.time}</span><span className="mp-moments__x">{m.text}</span></li>
          ))}
        </ul>
      </Section>

      {/* follow-up strategy */}
      {analysis.strategy && (
        <Section icon="Compass" title="Follow-up call strategy" subtitle={analysis.strategy.focus}>
          <div className="mp-strategy-banner"><Icon name="Sparkles" size={17} /><p>{analysis.strategy.headline}</p></div>
          <ol className="mp-agenda">
            {analysis.strategy.plays.map((p, i) => (
              <li key={i}>
                <span className="mp-pitch__num" style={{ marginTop: 1 }}>{i + 1}</span>
                <div><div className="mp-agenda__label">{p.label}</div><div className="mp-agenda__detail">{p.detail}</div></div>
              </li>
            ))}
          </ol>
        </Section>
      )}

      {/* next steps */}
      <Section icon="ListTodo" title="Next steps & follow-up actions" subtitle={"Ranked for a " + (analysis.companyType || "mid-market") + " deal like this one."}>
        <div className="mp-checklist">
          {steps.map((s, i) => (
            <button key={i} className="mp-checkitem" onClick={() => toggle(i)}>
              <span className={`mp-checkbox${s.done ? " is-done" : ""}`}>{s.done && <Icon name="Check" size={14} strokeWidth={3} />}</span>
              <span className={`mp-checkitem__text${s.done ? " is-done" : ""}`}>{s.text}</span>
            </button>
          ))}
        </div>
      </Section>

      {/* who to bring */}
      {analysis.roleFit && (
        <Section icon="Users" title="Roles to consider bringing to the follow-up" subtitle="The kind of teammate who strengthens the next conversation — and whether it's yours to run.">
          <TeamRecommender team={analysis.team || []} soloFit={analysis.roleFit} />
        </Section>
      )}

      {/* email */}
      <Section icon="Mail" title="Follow-up email" subtitle="Ready to send — tweak and go.">
        <div className="mp-email"><pre>{analysis.email}{userName}</pre></div>
        <Button variant="secondary" size="sm" icon="Copy" style={{ marginTop: 14 }}
          onClick={() => { try { navigator.clipboard.writeText(analysis.email + userName); } catch (e) {} toast.success("Email copied — ready to paste."); }}>
          Copy email
        </Button>
      </Section>

      {/* bottom bar */}
      <Card pad>
        <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 14 }}>
          <span style={{ fontSize: "var(--fs-subtitle-2)", fontWeight: 700, color: "var(--fg-1)" }}>Deal stage</span>
          <div style={{ minWidth: 180 }}>
            <Select value={stage} onChange={(e) => { setStage(e.target.value); MP.setDealStage(id, e.target.value); toast.success("Moved to " + e.target.value + "."); }}>
              {DEAL_STAGES.map(s => <option key={s} value={s}>{s}</option>)}
            </Select>
          </div>
          <div style={{ flex: 1 }}></div>
          <Button variant="ghost" size="sm" icon="RotateCcw" onClick={onReset}>Re-analyze</Button>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { PostCallPage, PostCallResult, Waveform, VERDICTS, DEAL_STAGES });
