/* KitRate — campaign quote intelligence, brand fit, and deal pipeline. */

function EvidenceRail({ evidence, confidence, compact = false }) {
  const verified = !!evidence?.verified;
  const sourceLabel = verified
    ? "Verified by platform"
    : evidence?.source === "estimate"
      ? "Draft estimate"
      : evidence?.source === "sample"
        ? "Sample data"
        : evidence?.source === "production_model"
          ? "Production model"
          : "Manually entered";
  return (
    <div className={"kr-evidence-rail" + (verified ? " verified" : "") + (compact ? " compact" : "")}>
      <span className="kr-evidence-dot"></span>
      <strong>{sourceLabel}</strong>
      {evidence?.metricWindow && evidence.metricWindow.toLowerCase() !== sourceLabel.toLowerCase() && <span>{evidence.metricWindow}</span>}
      {evidence?.sampleSize ? <span>{evidence.sampleSize} posts</span> : null}
      {evidence?.syncedAt && <span>Synced {new Date(evidence.syncedAt).toLocaleDateString()}</span>}
      {confidence?.label && <span>{confidence.label}</span>}
    </div>
  );
}

function QuoteBuilder({ profile, rates, onCreateDeal }) {
  const organic = rates.items.filter((item) => item.platform !== "UGC");
  const [itemId, setItemId] = useState(() => organic[0]?.id || rates.items[0]?.id || "");
  const [scope, setScope] = useState({
    quantity: 1,
    rights: "organic_30",
    exclusivity: "none",
    revisions: 1,
    productionHours: 7,
    directCosts: 0,
    whitelisting: false,
    rawFootage: false,
    rush: false
  });
  const [brand, setBrand] = useState("");
  const [toast, toastNode] = useToast();
  const item = rates.items.find((entry) => entry.id === itemId) || rates.items[0];
  const quote = KitRateQuote.quoteCampaign(item, scope, profile.businessTerms || {});
  const set = (patch) => setScope({ ...scope, ...patch });

  if (!item || !quote) {
    return <EmptyState icon="warn" title="Add a platform first" desc="A campaign quote needs at least one deliverable rate." />;
  }

  const counter = `${brand || "[Brand]"} campaign quote\n\n${scope.quantity} × ${item.label}\n${quote.lines.slice(1).map((line) => "• " + line.label).join("\n")}\n\nTarget: ${KitRateEngine.fmtMoney(quote.target)}\nOpening quote: ${KitRateEngine.fmtMoney(quote.anchor)}\n\nThe rate includes the scope above. Any extension of usage, paid amplification, exclusivity, or additional revisions is licensed separately.`;

  return (
    <div className="kr-intel-grid">
      <section className="kr-card kr-intel-controls">
        <div className="kr-eyebrow">Campaign scope</div>
        <h2 className="kr-serif">Build a defensible quote</h2>
        <p className="kr-intel-copy">Start with the deliverable, then price the rights and restrictions that brands often bury in a brief.</p>

        <Field label="Brand">
          <input className="kr-input" value={brand} placeholder="Brand or campaign name" onChange={(e) => setBrand(e.target.value)} />
        </Field>
        <Field label="Deliverable">
          <select className="kr-select" value={item.id} onChange={(e) => setItemId(e.target.value)}>
            {rates.items.map((entry) => <option key={entry.id} value={entry.id}>{entry.label}</option>)}
          </select>
        </Field>
        <div className="kr-form-pair">
          <Field label="Quantity">
            <input className="kr-input" type="number" min="1" max="50" value={scope.quantity} onChange={(e) => set({ quantity: +e.target.value })} />
          </Field>
          <Field label="Revision rounds">
            <input className="kr-input" type="number" min="0" max="10" value={scope.revisions} onChange={(e) => set({ revisions: +e.target.value })} />
          </Field>
        </div>
        <Field label="Content usage">
          <select className="kr-select" value={scope.rights} onChange={(e) => set({ rights: e.target.value })}>
            {Object.entries(KitRateQuote.RIGHTS).map(([value, row]) => <option key={value} value={value}>{row.label} (+{row.pct}%)</option>)}
          </select>
        </Field>
        <Field label="Category exclusivity">
          <select className="kr-select" value={scope.exclusivity} onChange={(e) => set({ exclusivity: e.target.value })}>
            {Object.entries(KitRateQuote.EXCLUSIVITY).map(([value, row]) => <option key={value} value={value}>{row.label}{row.pct ? " (+" + row.pct + "%)" : ""}</option>)}
          </select>
        </Field>
        <div className="kr-form-pair">
          <Field label="Production hours">
            <input className="kr-input" type="number" min="1" value={scope.productionHours} onChange={(e) => set({ productionHours: +e.target.value })} />
          </Field>
          <Field label="Direct costs">
            <input className="kr-input" inputMode="decimal" value={scope.directCosts} onChange={(e) => set({ directCosts: +e.target.value.replace(/[^0-9.]/g, "") || 0 })} />
          </Field>
        </div>
        <div className="kr-check-grid">
          {[
            ["whitelisting", "Paid amplification"],
            ["rawFootage", "Raw footage handoff"],
            ["rush", "Rush delivery"]
          ].map(([key, label]) => (
            <label key={key}><input type="checkbox" checked={scope[key]} onChange={(e) => set({ [key]: e.target.checked })} /> {label}</label>
          ))}
        </div>
      </section>

      <section className="kr-quote-sheet">
        <div className="kr-eyebrow">Negotiation range</div>
        <div className="kr-quote-triad">
          <div><span>Walk-away floor</span><strong>{KitRateEngine.fmtMoney(quote.floor)}</strong></div>
          <div className="target"><span>Target</span><strong>{KitRateEngine.fmtMoney(quote.target)}</strong></div>
          <div><span>Opening anchor</span><strong>{KitRateEngine.fmtMoney(quote.anchor)}</strong></div>
        </div>
        <EvidenceRail evidence={item.evidence} confidence={item.confidence} />
        <div className="kr-quote-lines">
          {quote.lines.map((line, index) => (
            <div key={index}>
              <span>{line.label}</span>
              <strong>{line.amount != null ? KitRateEngine.fmtMoney(line.amount) : "+" + line.pct + "%"}</strong>
            </div>
          ))}
          <div><span>Production-cost floor</span><strong>{KitRateEngine.fmtMoney(quote.productionFloor)}</strong></div>
        </div>
        {quote.warning && <div className="kr-scope-warning"><KrIcon d={ICONS.warn} size={15} /> {quote.warning}</div>}
        <div className="kr-quote-actions">
          <CopyBtn text={counter} toast={toast} label="Copy counteroffer" />
          <button className="kr-btn kr-btn-primary" onClick={() => {
            onCreateDeal({
              brandName: brand || "Unnamed brand",
              campaignName: item.label,
              stage: "negotiating",
              amount: quote.target,
              currency: "USD",
              deliverables: [{ itemId: item.id, label: item.label, quantity: scope.quantity }],
              rights: scope
            });
            toast("Added to deal pipeline");
          }}><KrIcon d={ICONS.plus} size={14} /> Add to deals</button>
        </div>
        {toastNode}
      </section>
    </div>
  );
}

function BrandFitRadar({ profile, onCreateDeal }) {
  const ranked = useMemo(() => KitRateBrandFit.rankBrandLeads(profile), [profile]);
  const [expanded, setExpanded] = useState(ranked[0]?.brand.id || null);
  return (
    <div>
      <SectionHead
        eyebrow="Transparent opportunity scoring"
        title="Brand Fit Radar"
        desc="These starter leads demonstrate the matching model. Scores use your niche, region, verified performance, campaign formats, and category proof. Campaign availability still needs verification."
      />
      <div className="kr-fit-list">
        {ranked.map((match) => {
          const open = expanded === match.brand.id;
          return (
            <article key={match.brand.id} className="kr-fit-row">
              <button className="kr-fit-summary" onClick={() => setExpanded(open ? null : match.brand.id)} aria-expanded={open}>
                <div className="kr-fit-score"><strong>{match.score}</strong><span>/100</span></div>
                <div className="kr-fit-main">
                  <div><strong>{match.brand.name}</strong><span className="kr-chip">{match.brand.status}</span></div>
                  <p>{match.brand.category} · Planning budget {match.brand.budgetBand}</p>
                  <div className="kr-fit-meter"><span style={{ width: match.score + "%" }}></span></div>
                </div>
                <span className={"kr-chip " + (match.score >= 78 ? "kr-chip-good" : match.score >= 58 ? "kr-chip-accent" : "kr-chip-warn")}>{match.label}</span>
              </button>
              {open && (
                <div className="kr-fit-detail">
                  <div>
                    <div className="kr-eyebrow">Why it fits</div>
                    {match.reasons.map((reason) => <p key={reason}><KrIcon d={ICONS.check} size={12} /> {reason}</p>)}
                  </div>
                  <div>
                    <div className="kr-eyebrow">Before pitching</div>
                    {match.cautions.length ? match.cautions.map((caution) => <p key={caution}><KrIcon d={ICONS.warn} size={12} /> {caution}</p>) : <p><KrIcon d={ICONS.check} size={12} /> No major fit cautions detected.</p>}
                  </div>
                  <button className="kr-btn kr-btn-primary kr-btn-sm" onClick={() => onCreateDeal({
                    brandName: match.brand.name,
                    campaignName: match.brand.category,
                    stage: "lead",
                    amount: null,
                    currency: "USD",
                    fitScore: match.score,
                    deliverables: [],
                    rights: {}
                  })}>Add lead <KrIcon d={ICONS.arrowRight} size={12} /></button>
                </div>
              )}
            </article>
          );
        })}
      </div>
    </div>
  );
}

const DEAL_STAGES = [
  ["lead", "Lead"],
  ["pitched", "Pitched"],
  ["negotiating", "Negotiating"],
  ["won", "Won"],
  ["completed", "Completed"]
];

function DealsPipeline({ deals, setDeals, saveDeal, removeDeal }) {
  const [draft, setDraft] = useState("");
  const add = () => {
    if (!draft.trim()) return;
    saveDeal({ brandName: draft.trim(), campaignName: "", stage: "lead", amount: null, currency: "USD", deliverables: [], rights: {}, outcome: {} });
    setDraft("");
  };
  return (
    <div>
      <SectionHead
        eyebrow="Deal intelligence"
        title="Partnership pipeline"
        desc="Capture offers, negotiated rates, rights, and outcomes. Completed deals become the evidence base for better future pricing."
        right={<div className="kr-deal-add"><input className="kr-input" value={draft} placeholder="Add a brand lead" onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => e.key === "Enter" && add()} /><button className="kr-btn kr-btn-primary" disabled={!draft.trim()} onClick={add}><KrIcon d={ICONS.plus} size={14} /> Add</button></div>}
      />
      <div className="kr-pipeline">
        {DEAL_STAGES.map(([stage, label]) => {
          const rows = deals.filter((deal) => deal.stage === stage);
          return (
            <section key={stage} className="kr-pipeline-col">
              <header><span>{label}</span><strong>{rows.length}</strong></header>
              {rows.map((deal) => (
                <article key={deal.id} className="kr-deal-card">
                  <div className="kr-deal-title"><strong>{deal.brandName}</strong><button onClick={() => removeDeal(deal.id)} aria-label={"Delete " + deal.brandName}><KrIcon d={ICONS.x} size={12} /></button></div>
                  <input value={deal.campaignName || ""} placeholder="Campaign"
                    onChange={(e) => setDeals((current) => current.map((row) => row.id === deal.id ? { ...row, campaignName: e.target.value } : row))}
                    onBlur={(e) => saveDeal({ ...deal, campaignName: e.currentTarget.value })} />
                  <div className="kr-deal-money"><span>$</span><input inputMode="decimal" value={deal.amount ?? ""} placeholder="Offer"
                    onChange={(e) => setDeals((current) => current.map((row) => row.id === deal.id ? { ...row, amount: +e.target.value.replace(/[^0-9.]/g, "") || null } : row))}
                    onBlur={(e) => saveDeal({ ...deal, amount: +e.currentTarget.value.replace(/[^0-9.]/g, "") || null })} /></div>
                  {deal.fitScore != null && <span className="kr-chip kr-chip-accent">{deal.fitScore} fit</span>}
                  <select value={deal.stage} onChange={(e) => saveDeal({ ...deal, stage: e.target.value })}>
                    {DEAL_STAGES.map(([value, stageLabel]) => <option key={value} value={value}>{stageLabel}</option>)}
                  </select>
                  {["won", "completed"].includes(deal.stage) && (
                    <details className="kr-outcome">
                      <summary>Outcome & profitability</summary>
                      <label>Hours worked<input type="number" min="0" value={deal.outcome?.hours ?? ""}
                        onChange={(e) => setDeals((current) => current.map((row) => row.id === deal.id ? { ...row, outcome: { ...(row.outcome || {}), hours: +e.target.value || null } } : row))}
                        onBlur={(e) => saveDeal({ ...deal, outcome: { ...(deal.outcome || {}), hours: +e.currentTarget.value || null } })} /></label>
                      <label>Campaign views<input inputMode="numeric" value={deal.outcome?.views ?? ""}
                        onChange={(e) => setDeals((current) => current.map((row) => row.id === deal.id ? { ...row, outcome: { ...(row.outcome || {}), views: +e.target.value.replace(/\D/g, "") || null } } : row))}
                        onBlur={(e) => saveDeal({ ...deal, outcome: { ...(deal.outcome || {}), views: +e.currentTarget.value.replace(/\D/g, "") || null } })} /></label>
                      {deal.amount && deal.outcome?.hours ? (
                        <div className="kr-effective-rate"><span>Effective hourly</span><strong>{KitRateEngine.fmtMoney(deal.amount / deal.outcome.hours)}</strong></div>
                      ) : null}
                    </details>
                  )}
                </article>
              ))}
              {!rows.length && <p className="kr-pipeline-empty">No {label.toLowerCase()} deals.</p>}
            </section>
          );
        })}
      </div>
    </div>
  );
}

function KitAnalyticsPanel({ slug, analytics, onRefresh }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  useEffect(() => {
    if (!slug || analytics) return;
    setLoading(true);
    onRefresh().catch((nextError) => setError(nextError.message)).finally(() => setLoading(false));
  }, [slug]);

  if (!slug) {
    return <EmptyState icon="eye" title="Publish your kit first" desc="Open Media kit, choose Share link, and publish a snapshot to start measuring real brand visits." />;
  }
  if (loading) {
    return <EmptyState icon="clock" title="Loading kit analytics" desc="Reading public visits and rate-card attention." />;
  }
  if (error) {
    return <EmptyState icon="warn" title="Analytics unavailable" desc={error} action={<button className="kr-btn kr-btn-secondary" onClick={() => { setError(null); setLoading(true); onRefresh().catch((nextError) => setError(nextError.message)).finally(() => setLoading(false)); }}>Try again</button>} />;
  }
  const data = analytics || { opens: 0, uniqueVisitors: 0, totalDwell: 0, brands: [] };
  const avgDwell = data.opens ? Math.round(data.totalDwell / data.opens) : 0;
  return (
    <div>
      <SectionHead eyebrow="Public-kit evidence" title="Brand attention"
        desc="Only public visits count here. Creator previews are kept separate."
        right={<button className="kr-btn kr-btn-secondary" onClick={() => { setLoading(true); onRefresh().catch((nextError) => setError(nextError.message)).finally(() => setLoading(false)); }}><KrIcon d={ICONS.refresh} size={14} /> Refresh</button>} />
      <div className="kr-analytics-strip">
        <div><span>Total opens</span><strong>{data.opens}</strong></div>
        <div><span>Unique visitors</span><strong>{data.uniqueVisitors}</strong></div>
        <div><span>Avg rate-card dwell</span><strong>{avgDwell ? avgDwell + "s" : "—"}</strong></div>
        <div><span>Last opened</span><strong>{data.lastOpened ? new Date(data.lastOpened).toLocaleDateString() : "—"}</strong></div>
      </div>
      <section className="kr-card kr-analytics-table">
        <div className="kr-eyebrow">By brand link</div>
        {(data.brands || []).length ? (data.brands || []).map((brand) => (
          <div key={brand.brand_slug || "general"}>
            <strong>{brand.brand_slug ? brand.brand_slug.replace(/-/g, " ") : "General kit link"}</strong>
            <span>{brand.opens} open{brand.opens === 1 ? "" : "s"}</span>
            <span>{Math.round(brand.total_dwell || 0)}s rate-card dwell</span>
            <span>{brand.last_opened ? new Date(brand.last_opened).toLocaleDateString() : "—"}</span>
          </div>
        )) : <p className="kr-pipeline-empty">No public opens yet.</p>}
      </section>
    </div>
  );
}

function IntelligenceDashboard({ profile, rates, deals, setDeals, saveDeal, removeDeal, publishedSlug, analytics, onRefreshAnalytics, initialTab = "quote" }) {
  const [tab, setTab] = useState(initialTab);
  const createDeal = (deal) => {
    saveDeal(deal);
    setTab("deals");
  };
  return (
    <main className="kr-intelligence-page" data-screen-label="Deal intelligence">
      <div className="kr-intel-tabs">
        {[
          ["quote", "Quote builder"],
          ["brands", "Brand Fit Radar"],
          ["deals", "Deals"],
          ["analytics", "Kit analytics"]
        ].map(([value, label]) => (
          <button key={value} className={tab === value ? "active" : ""} onClick={() => setTab(value)}>{label}</button>
        ))}
      </div>
      {tab === "quote" && <QuoteBuilder profile={profile} rates={rates} onCreateDeal={createDeal} />}
      {tab === "brands" && <BrandFitRadar profile={profile} onCreateDeal={createDeal} />}
      {tab === "deals" && <DealsPipeline deals={deals} setDeals={setDeals} saveDeal={saveDeal} removeDeal={removeDeal} />}
      {tab === "analytics" && <KitAnalyticsPanel slug={publishedSlug} analytics={analytics} onRefresh={onRefreshAnalytics} />}
    </main>
  );
}

Object.assign(window, { EvidenceRail, QuoteBuilder, BrandFitRadar, DealsPipeline, KitAnalyticsPanel, IntelligenceDashboard });
