/* Call detail page + 404 + empty states + tenant-detail tabs */

const CallDetail = ({ onGo }) => {
  const [playing, setPlaying] = useState(false);
  const store = MK_USE();
  const call = (store.recentCalls || [])[0] || null;
  const [transcript, setTranscript] = useState([]);
  useEffect(() => {
    let alive = true;
    const callId = call?.id;
    if (!callId) {
      setTranscript([]);
      return () => { alive = false; };
    }
    api.calls.get(callId).then((data) => {
      if (!alive) return;
      const rows = Array.isArray(data?.messages) ? data.messages : Array.isArray(data) ? data : [];
      const normalized = rows.map((m, index) => ({
        who: m.role === "assistant" || m.who === "agent" ? "agent" : "caller",
        t: m.text || m.content || "",
        at: m.at || m.timestamp || `0:${String(index).padStart(2, "0")}`,
      }));
      setTranscript(normalized);
    }).catch(() => {
      if (!alive) return;
      setTranscript([]);
    });
    return () => { alive = false; };
  }, [call?.id]);
  const durationLabel = call?.duration_seconds ? `${Math.floor(call.duration_seconds / 60)}:${String(call.duration_seconds % 60).padStart(2, "0")}` : "0:00";
  const outcome = call?.status || "unknown";
  const caller = call?.caller_number || "Unknown";
  return (
    <div className="page page-mount">
      <div className="row gap-2" style={{ marginBottom: 12, fontSize: 13, color: "var(--fg-muted)" }}>
        <a className="dot-link" onClick={() => onGo("tenant-calls")}>Calls</a> / <span>Call · {durationLabel}</span>
      </div>
      <div className="page-header">
        <div>
          <div className="row gap-3" style={{ marginBottom: 6 }}>
            <Chip kind={outcome === "completed" ? "live" : "warn"} dot>{outcome}</Chip>
            <span className="mono cell-strong" style={{ fontSize: 16 }}>{caller}</span>
            <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>{call?.created_at ? new Date(call.created_at).toLocaleString() : "—"} · {durationLabel}</span>
          </div>
          <h1 className="page-title">{call?.transcript_summary || "Call details"}</h1>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline"><Icon name="download"/> Export</button>
          <button className="btn btn-outline"><Icon name="phone"/> Call back</button>
          <button className="btn btn-primary">Actions <Icon name="chevron-down"/></button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "2fr 1fr", gap: 20 }}>
        <div className="stack gap-4">
          <div className="card card-pad">
            <div className="row between" style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Recording</div>
              <span className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>2:14 · 22 kHz · stereo</span>
            </div>
            <div className="row gap-3" style={{ padding: 14, background: "var(--bg-sunken)", borderRadius: 12 }}>
              <button className="btn btn-accent btn-icon" onClick={() => setPlaying(p => !p)}><Icon name={playing ? "pause" : "play"} size={16}/></button>
              <div style={{ flex: 1 }}>
                <div className="wave" style={{ height: 36, gap: 2, width: "100%" }}>
                  {Array.from({ length: 80 }).map((_, i) => (
                    <span key={i} style={{ height: (10 + Math.abs(Math.sin(i * 0.7)) * 22) + "px", width: 3, opacity: playing && i < 30 ? 1 : 0.5, background: playing && i < 30 ? "var(--mk-orange)" : "var(--mk-slate-400)" }}/>
                  ))}
                </div>
                <div className="row between" style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 4 }}><span className="mono">0:42</span><span className="mono">2:14</span></div>
              </div>
              <button className="btn btn-ghost btn-icon" title="Download"><Icon name="download" size={14}/></button>
            </div>
          </div>

          <div className="card">
            <div className="row between" style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Transcript</div>
              <button className="btn btn-ghost btn-sm"><Icon name="download" size={13}/> .txt</button>
            </div>
            <div className="stack gap-3" style={{ padding: 20 }}>
              {transcript.length === 0 ? (
                <div style={{ color: "var(--fg-muted)" }}>No transcript available for this call yet.</div>
              ) : transcript.map((m, i) => (
                <div key={i} className="row gap-3" style={{ alignItems: "flex-start" }}>
                  <div className="avatar" style={{ width: 28, height: 28, fontSize: 10, background: m.who === "agent" ? "var(--mk-orange)" : "var(--mk-ink)" }}>{m.who === "agent" ? "AI" : "JN"}</div>
                  <div style={{ flex: 1 }}>
                    <div className="row gap-2" style={{ marginBottom: 3 }}>
                      <span style={{ fontSize: 12.5, fontWeight: 500, color: m.who === "agent" ? "var(--mk-orange-600)" : "var(--fg)" }}>{m.who === "agent" ? "Mikaka" : "Joyce"}</span>
                      <span className="mono" style={{ fontSize: 11, color: "var(--fg-faint)" }}>{m.at}</span>
                    </div>
                    <div style={{ fontSize: 14, lineHeight: 1.55, color: "var(--fg)" }}>{m.t}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="stack gap-4">
          <div className="card card-pad">
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 14 }}>Outcome</div>
            <div className="stack gap-3" style={{ fontSize: 13.5 }}>
              <div className="row between"><span style={{ color: "var(--fg-muted)" }}>Intent</span><span>Book appointment</span></div>
              <div className="row between"><span style={{ color: "var(--fg-muted)" }}>Action</span><Chip kind={outcome === "completed" ? "live" : "warn"} dot>{outcome}</Chip></div>
              <div className="row between"><span style={{ color: "var(--fg-muted)" }}>Call id</span><span className="mono">{call?.id || "—"}</span></div>
              <div className="row between"><span style={{ color: "var(--fg-muted)" }}>Pipeline</span><span>{call?.pipeline || "—"}</span></div>
              <div className="row between"><span style={{ color: "var(--fg-muted)" }}>Sentiment</span><span>{call?.sentiment || "n/a"}</span></div>
              <div className="row between"><span style={{ color: "var(--fg-muted)" }}>Language</span><span>{call?.language || "n/a"}</span></div>
            </div>
          </div>
          <div className="card card-pad">
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 12 }}>Caller</div>
            <div className="row gap-3">
              <div className="avatar" style={{ width: 36, height: 36, fontSize: 12 }}>JN</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 14 }}>{call?.caller_name || "Caller"}</div>
                <div className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{caller}</div>
                <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 4 }}>{call?.caller_stats || "Recent call activity unavailable"}</div>
              </div>
            </div>
          </div>
          <div className="card card-pad">
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 10 }}>Quality</div>
            <div className="stack gap-2" style={{ fontSize: 13 }}>
              {[["Scripted accuracy", 96], ["Latency", 88], ["Intent match", 100]].map(([n, p]) => (
                <div key={n}><div className="row between" style={{ marginBottom: 3 }}><span style={{ color: "var(--fg-muted)" }}>{n}</span><span className="mono">{p}%</span></div>
                  <div style={{ height: 4, background: "var(--bg-sunken)", borderRadius: 3 }}><div style={{ width: p + "%", height: "100%", background: "var(--mk-orange)", borderRadius: 3 }}/></div></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const NotFound = ({ onGo }) => (
  <div style={{ minHeight: "calc(100vh - 65px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 40 }}>
    <div style={{ maxWidth: 520, textAlign: "center" }}>
      <div className="display" style={{ fontSize: 120, fontWeight: 600, letterSpacing: "-0.05em", color: "var(--mk-orange)", lineHeight: 1 }}>404</div>
      <h1 className="display" style={{ fontSize: 32, fontWeight: 600, letterSpacing: "-0.02em", margin: "16px 0 8px" }}>This number isn't in service.</h1>
      <p style={{ color: "var(--fg-muted)", marginBottom: 28 }}>The page you're looking for doesn't exist or has been moved.</p>
      <div className="row gap-2" style={{ justifyContent: "center" }}>
        <button className="btn btn-outline" onClick={() => history.back()}>← Back</button>
        <button className="btn btn-accent" onClick={() => onGo("tenant-dashboard")}>Take me home <Icon name="arrow-right"/></button>
      </div>
    </div>
  </div>
);

Object.assign(window, { CallDetail, NotFound });
