// ai-ui.jsx — AI UI components: risk scoring, reply generator, insights, NL search
const { useState: useStateAI, useEffect: useEffectAI, useRef: useRefAI } = React;

/* ---------- compact risk chip (tables) ---------- */
function RiskChip({ row, size = "sm" }) {
  const r = riskScore(row);
  const b = RISK_BAND[r.band];
  return (
    <span className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] font-semibold tabular-nums"
      style={{ background: b.bg, color: b.color }} title={`AI risk score ${r.score}/100 — ${b.label}`}>
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: b.bar }} />{r.score}
    </span>
  );
}

/* ---------- risk score panel (Smart Prioritization) ---------- */
function RiskPanel({ row }) {
  const r = riskScore(row);
  const b = RISK_BAND[r.band];
  return (
    <div className="px-5 py-4 border-b border-zinc-100">
      <div className="flex items-center gap-2 mb-3">
        <Icon name="trend_up" size={14} className="text-zinc-500" />
        <span className="text-[12px] font-semibold text-zinc-700">AI Priority Score</span>
        <span className="ml-auto text-[10px] font-medium text-zinc-400 px-1.5 py-0.5 rounded bg-zinc-100">auto-scored</span>
      </div>

      {/* score gauge */}
      <div className="flex items-center gap-3 mb-3">
        <div className="flex items-baseline gap-1">
          <span className="text-[28px] font-semibold tabular-nums leading-none" style={{ color: b.color }}>{r.score}</span>
          <span className="text-[12px] text-zinc-400">/100</span>
        </div>
        <div className="flex-1">
          <div className="flex items-center justify-between mb-1">
            <span className="inline-flex items-center gap-1.5 text-[11.5px] font-semibold" style={{ color: b.color }}>
              <span className="w-1.5 h-1.5 rounded-full" style={{ background: b.bar }} />{b.label}
            </span>
          </div>
          <div className="h-1.5 rounded-full bg-zinc-100 overflow-hidden">
            <div className="h-full rounded-full transition-all" style={{ width: r.score + "%", background: b.bar }} />
          </div>
        </div>
      </div>

      {/* reasons */}
      <div className="space-y-1.5">
        <div className="text-[10.5px] font-medium uppercase tracking-wide text-zinc-400">Contributing factors</div>
        {r.reasons.map(rs => (
          <div key={rs.key} className="flex items-center gap-2.5 rounded-lg border border-zinc-200 bg-zinc-50/60 px-2.5 py-1.5">
            <span className="flex items-center justify-center w-6 h-6 rounded-md bg-white border border-zinc-200 text-zinc-500 shrink-0"><Icon name={rs.icon} size={12} /></span>
            <div className="min-w-0 flex-1 leading-tight">
              <div className="text-[12px] font-medium text-zinc-700">{rs.label}</div>
              <div className="text-[11px] text-zinc-400 truncate">{rs.detail}</div>
            </div>
            <span className="text-[11px] font-semibold text-zinc-400 tabular-nums">+{rs.weight}</span>
          </div>
        ))}
        {r.reasons.length === 0 && <div className="text-[12px] text-zinc-400">No elevated risk factors detected.</div>}
      </div>
    </div>
  );
}

/* ---------- structured auto-summary ---------- */
function AutoSummary({ row, loading }) {
  const esc = escalationRec(row);
  const el = ESC_LEVEL[esc.level];
  if (loading) {
    return (
      <div className="px-5 py-4 border-b border-zinc-100 space-y-2">
        <Skeleton className="h-3 w-full" /><Skeleton className="h-3 w-[92%]" /><Skeleton className="h-3 w-[70%]" />
      </div>
    );
  }
  return (
    <div className="px-5 py-4 border-b border-zinc-100">
      <div className="flex items-center gap-2 mb-3">
        <span className="flex items-center justify-center w-5 h-5 rounded-md" style={{ background: "var(--accent-wash)" }}><Icon name="sparkles" size={13} style={{ color: "var(--accent)" }} /></span>
        <span className="text-[12px] font-semibold text-zinc-700">AI Auto-Summary</span>
        <span className="text-[10px] font-medium text-zinc-400 px-1.5 py-0.5 rounded bg-zinc-100">OpsPilot</span>
      </div>

      <div className="space-y-3">
        <div>
          <div className="text-[10.5px] font-medium uppercase tracking-wide text-zinc-400 mb-1">Issue summary</div>
          <p className="text-[13px] leading-relaxed text-zinc-600">{row.summary}</p>
        </div>
        <div>
          <div className="text-[10.5px] font-medium uppercase tracking-wide text-zinc-400 mb-1">Recommended next step</div>
          <div className="rounded-lg p-2.5 border flex items-start gap-2" style={{ background: "var(--accent-wash)", borderColor: "var(--accent-border)" }}>
            <Icon name="arrow_r" size={13} style={{ color: "var(--accent-ink)" }} className="mt-0.5 shrink-0" />
            <p className="text-[12.5px] leading-relaxed" style={{ color: "var(--accent-ink)" }}>{row.action}</p>
          </div>
        </div>
        <div>
          <div className="text-[10.5px] font-medium uppercase tracking-wide text-zinc-400 mb-1">Escalation recommendation</div>
          <div className="rounded-lg px-2.5 py-2 flex items-center gap-2" style={{ background: el.bg }}>
            <Icon name={el.icon} size={13} style={{ color: el.color }} className="shrink-0" />
            <span className="text-[12.5px] font-medium" style={{ color: el.color }}>{esc.text}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- multi-channel / tone reply generator ---------- */
function ReplyGenerator({ row, onLogged }) {
  const pref = signalsFor(row.id).channelPref;
  const [channel, setChannel] = useStateAI(pref);
  const [tone, setTone] = useStateAI("professional");
  const [state, setState] = useStateAI("idle"); // idle | loading | ready
  const [text, setText] = useStateAI("");
  const [copied, setCopied] = useStateAI(false);

  // reset when order changes
  useEffectAI(() => { setState("idle"); setText(""); setCopied(false); setChannel(signalsFor(row.id).channelPref); setTone("professional"); }, [row.id]);

  function generate(ch = channel, tn = tone) {
    setState("loading"); setText("");
    setTimeout(() => { setText(composeReply(row, ch, tn)); setState("ready"); onLogged && onLogged(row, ch); }, 750);
  }
  function pickChannel(ch) { setChannel(ch); if (state === "ready") generate(ch, tone); }
  function pickTone(tn) { setTone(tn); if (state === "ready") generate(channel, tn); }
  function copy() { navigator.clipboard?.writeText(text).catch(() => {}); setCopied(true); setTimeout(() => setCopied(false), 1500); }

  const chMeta = CHANNELS.find(c => c.key === channel);

  return (
    <div className="px-5 py-4 border-b border-zinc-100">
      <div className="flex items-center gap-2 mb-3">
        <Icon name="chat" size={14} className="text-zinc-500" />
        <span className="text-[12px] font-semibold text-zinc-700">AI Reply Generator</span>
        {signalsFor(row.id).channelPref && <span className="ml-auto text-[10.5px] text-zinc-400">Suggested: {CHANNELS.find(c=>c.key===pref)?.label}</span>}
      </div>

      {/* channel segmented */}
      <div className="inline-flex items-center gap-0.5 p-0.5 rounded-lg bg-zinc-100 border border-zinc-200 w-full mb-2">
        {CHANNELS.map(c => {
          const on = channel === c.key;
          return (
            <button key={c.key} onClick={() => pickChannel(c.key)}
              className={`flex-1 inline-flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[12px] font-medium transition-all ${on ? "bg-white text-zinc-800 shadow-sm" : "text-zinc-500 hover:text-zinc-700"}`}>
              <Icon name={c.icon} size={13} />{c.label}
            </button>
          );
        })}
      </div>

      {/* tone chips */}
      <div className="flex items-center gap-1.5 flex-wrap mb-3">
        <span className="text-[11px] text-zinc-400">Tone</span>
        {TONES.map(tn => {
          const on = tone === tn.key;
          return (
            <button key={tn.key} onClick={() => pickTone(tn.key)}
              className={`px-2 py-0.5 rounded-md text-[11.5px] font-medium border transition-all ${on ? "text-white border-transparent" : "bg-white text-zinc-600 border-zinc-200 hover:border-zinc-300"}`}
              style={on ? { background: "var(--accent)" } : undefined}>
              {tn.label}
            </button>
          );
        })}
      </div>

      {/* generate / output */}
      {state === "idle" && (
        <Button variant="default" size="sm" icon="sparkles" full onClick={() => generate()}>Generate {chMeta.label} reply</Button>
      )}

      {state === "loading" && (
        <div className="rounded-lg border border-zinc-200 p-3 space-y-2">
          <div className="flex items-center gap-2 text-[12px] text-zinc-400"><Icon name="sparkles" size={13} className="animate-pulse" style={{ color: "var(--accent)" }} />Drafting {chMeta.label.toLowerCase()} reply…</div>
          <Skeleton className="h-3 w-full" /><Skeleton className="h-3 w-[88%]" /><Skeleton className="h-3 w-[94%]" />
        </div>
      )}

      {state === "ready" && (
        <div>
          <ReplyPreview channel={channel} text={text} customer={row.customer} />
          <div className="flex items-center gap-2 mt-2.5">
            {channel === "internal"
              ? <Button variant="primary" size="sm" icon="escalate">Post to channel</Button>
              : <Button variant="primary" size="sm" icon="send">Send via {chMeta.label}</Button>}
            <Button variant="default" size="sm" icon={copied ? "check" : "copy"} onClick={copy}>{copied ? "Copied" : "Copy"}</Button>
            <button onClick={() => generate()} className="ml-auto text-[12px] text-zinc-400 hover:text-zinc-600 inline-flex items-center gap-1"><Icon name="refresh" size={13} /> Regenerate</button>
          </div>
        </div>
      )}
    </div>
  );
}

// channel-styled preview (subtle, not skeuomorphic)
function ReplyPreview({ channel, text, customer }) {
  if (channel === "email") {
    const lines = text.split("\n");
    const subject = (lines[0] || "").replace(/^Subject:\s*/, "");
    const body = lines.slice(1).join("\n").trim();
    return (
      <div className="rounded-lg border border-zinc-200 overflow-hidden">
        <div className="px-3 py-2 bg-zinc-50 border-b border-zinc-100 text-[11.5px] text-zinc-500 space-y-0.5">
          <div><span className="text-zinc-400">To:</span> <span className="text-zinc-700">{customer.email}</span></div>
          <div><span className="text-zinc-400">Subject:</span> <span className="text-zinc-700 font-medium">{subject}</span></div>
        </div>
        <div className="p-3 text-[12.5px] leading-relaxed text-zinc-700 whitespace-pre-line">{body}</div>
      </div>
    );
  }
  if (channel === "internal") {
    return (
      <div className="rounded-lg border border-zinc-200 bg-zinc-50/70 p-3 text-[12px] leading-relaxed text-zinc-700 font-mono whitespace-pre-line">{text}</div>
    );
  }
  // whatsapp — a single subtle bubble
  return (
    <div className="rounded-lg border border-zinc-200 bg-zinc-50/40 p-3">
      <div className="rounded-xl rounded-tl-sm bg-white border border-zinc-200 px-3 py-2 text-[12.5px] leading-relaxed text-zinc-700 whitespace-pre-line max-w-[92%]">{text}</div>
      <div className="text-[10.5px] text-zinc-400 mt-1.5 pl-1 flex items-center gap-1"><Icon name="chat" size={11} /> WhatsApp Business · draft</div>
    </div>
  );
}

/* ---------- AI Insights panel (dashboard) ---------- */
function InsightsPanel({ onAction }) {
  return (
    <div>
      <div className="flex items-center gap-2 mb-3">
        <span className="flex items-center justify-center w-5 h-5 rounded-md" style={{ background: "var(--accent-wash)" }}><Icon name="sparkles" size={13} style={{ color: "var(--accent)" }} /></span>
        <h2 className="text-[14px] font-semibold text-zinc-900 tracking-tight">AI Operational Insights</h2>
        <span className="text-[11.5px] text-zinc-400">· generated from 1,284 orders · updated 5 min ago</span>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3.5">
        {INSIGHTS.map(ins => {
          const t = INSIGHT_TONE[ins.tone];
          return (
            <div key={ins.id} className="bg-white rounded-xl border border-zinc-200 p-4 flex flex-col">
              <div className="flex items-center justify-between mb-2.5">
                <span className="flex items-center justify-center w-8 h-8 rounded-lg" style={{ background: t.bg, color: t.color }}><Icon name={ins.icon} size={16} /></span>
                <span className="inline-flex items-center gap-1 text-[11px] font-semibold px-1.5 py-0.5 rounded-md tabular-nums" style={{ background: t.bg, color: t.color }}>
                  <Icon name={ins.trend === "up" ? "trend_up" : ins.trend === "down" ? "trend_dn" : "arrow_r"} size={11} strokeWidth={2.25} />{ins.delta}
                </span>
              </div>
              <h3 className="text-[13px] font-semibold text-zinc-800 leading-snug">{ins.headline}</h3>
              <p className="text-[11.5px] text-zinc-500 leading-snug mt-1 flex-1">{ins.detail}</p>
              <button onClick={() => onAction(ins.action.page)} className="mt-2.5 self-start text-[12px] font-medium inline-flex items-center gap-1" style={{ color: "var(--accent-ink)" }}>
                {ins.action.label} <Icon name="arrow_r" size={12} />
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- AI natural-language search overlay ---------- */
function AISearchOverlay({ open, onClose, onSelect }) {
  const [q, setQ] = useStateAI("");
  const [result, setResult] = useStateAI({ filters: [], rows: [] });
  const inputRef = useRefAI(null);

  useEffectAI(() => { if (open) { setTimeout(() => inputRef.current?.focus(), 50); } else { setQ(""); setResult({ filters: [], rows: [] }); } }, [open]);
  useEffectAI(() => { setResult(parseSearch(q)); }, [q]);
  useEffectAI(() => {
    function onKey(e) { if (e.key === "Escape") onClose(); }
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  if (!open) return null;
  const hasQuery = q.trim().length > 0;

  return (
    <div className="fixed inset-0 z-[55] flex items-start justify-center pt-[12vh] px-4 bg-zinc-900/40 backdrop-blur-[1px]" onClick={onClose}>
      <div className="w-full max-w-[620px] bg-white rounded-2xl shadow-2xl border border-zinc-200 overflow-hidden animate-[toastin_0.15s_ease]" onClick={e => e.stopPropagation()}>
        {/* input */}
        <div className="flex items-center gap-2.5 px-4 h-14 border-b border-zinc-100">
          <Icon name="sparkles" size={18} style={{ color: "var(--accent)" }} />
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Ask in plain language — e.g. “delayed Honda orders over 2 days”"
            className="flex-1 bg-transparent outline-none text-[14px] text-zinc-800 placeholder:text-zinc-400" />
          <kbd className="text-[10px] text-zinc-400 border border-zinc-300 rounded px-1.5 py-0.5">Esc</kbd>
        </div>

        {/* interpreted filters */}
        {hasQuery && result.filters.length > 0 && (
          <div className="flex items-center gap-1.5 px-4 py-2.5 border-b border-zinc-100 flex-wrap">
            <span className="text-[11px] font-medium text-zinc-400">Interpreted as</span>
            {result.filters.map((f, i) => (
              <span key={i} className="inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[11.5px] font-medium" style={{ background: "var(--accent-wash)", color: "var(--accent-ink)" }}>
                <Icon name={f.icon} size={11} />{f.label}
              </span>
            ))}
          </div>
        )}

        {/* body */}
        <div className="max-h-[46vh] overflow-y-auto">
          {!hasQuery ? (
            <div className="p-4">
              <div className="text-[11px] font-medium uppercase tracking-wide text-zinc-400 mb-2">Try asking</div>
              <div className="space-y-1">
                {SEARCH_EXAMPLES.map(ex => (
                  <button key={ex} onClick={() => setQ(ex)} className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left hover:bg-zinc-50 transition-colors">
                    <Icon name="search" size={14} className="text-zinc-400" />
                    <span className="text-[13px] text-zinc-600">{ex}</span>
                  </button>
                ))}
              </div>
            </div>
          ) : result.rows.length === 0 ? (
            <div className="px-4 py-10 text-center text-[13px] text-zinc-400">No orders match that query.</div>
          ) : (
            <div className="py-1.5">
              <div className="px-4 py-1.5 text-[11px] font-medium text-zinc-400">{result.rows.length} match{result.rows.length !== 1 ? "es" : ""} · sorted by AI risk</div>
              {result.rows.map(r => (
                <button key={r.id} onClick={() => { onSelect(r); onClose(); }} className="w-full flex items-center gap-3 px-4 py-2 hover:bg-zinc-50 transition-colors text-left">
                  <Avatar person={r.customer} size={30} />
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="text-[13px] font-medium text-zinc-800 truncate">{r.customer.name}</span>
                      <span className="font-mono text-[11px] text-zinc-400">{r.id}</span>
                    </div>
                    <div className="text-[11.5px] text-zinc-400 truncate">{r.car} · {r.issue}</div>
                  </div>
                  <RiskChip row={r} />
                  <PriorityBadge level={r.priority} />
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RiskChip, RiskPanel, AutoSummary, ReplyGenerator, ReplyPreview, InsightsPanel, AISearchOverlay });
