// =================================================================
// pw-connection.jsx — runtime connection controls.
//   ConnectionBadge   — clickable top-bar pill (mode + env + status dot)
//   ConnectionModal   — switch mock/live, environment, baseUrl override,
//                       test connection, and view the live request log
//   Drives window.__api.setConfig() → app re-bootstraps → UI goes live.
// =================================================================

const STATUS_META = {
  mock:       { dot: "var(--muted-2)", label: "Mock" },
  unknown:    { dot: "var(--warn)",    label: "Live" },
  connecting: { dot: "var(--warn)",    label: "Connecting" },
  live:       { dot: "var(--good)",    label: "Live" },
  error:      { dot: "var(--bad)",     label: "Error" },
};

const ConnectionBadge = ({ onClick }) => {
  const status = useConnStatus();
  const conn = window.__api.getConfig();
  const meta = STATUS_META[status.state] || STATUS_META.mock;
  return (
    <button className="pw-conn-badge" onClick={onClick} title={status.detail || "Connection settings"}>
      <span className={`pw-conn-dot ${status.state === "connecting" ? "pulse" : ""}`} style={{ background: meta.dot }}/>
      <span className="pw-conn-mode">{conn.live ? "Live" : "Mock"}</span>
      <span className="pw-conn-env">{conn.environment}</span>
    </button>
  );
};

const RequestLog = () => {
  const [items, setItems] = React.useState(window.__api.getLog());
  React.useEffect(() => window.__api.on("log", () => setItems(window.__api.getLog())), []);
  if (!items.length) return <div className="pw-log-empty">No requests yet. Interact with the app to see calls here.</div>;
  return (
    <div className="pw-log">
      {items.map(e => (
        <div key={e.id} className="pw-log-row">
          <span className={`pw-log-method m-${e.method}`}>{e.method}</span>
          <span className="pw-log-url" title={e.url}>{e.url}</span>
          <span className={`pw-log-mode ${e.mode}`}>{e.mode}</span>
          <span className={`pw-log-status ${e.ok ? "ok" : "bad"}`}>{e.status || (e.error || "ERR")}</span>
        </div>
      ))}
    </div>
  );
};

const ConnectionModal = ({ open, onClose }) => {
  const live0 = window.__api.getConfig();
  const [mode, setMode] = React.useState(live0.mode);
  const [environment, setEnvironment] = React.useState(live0.environment);
  const [overrideUrl, setOverrideUrl] = React.useState(live0.overrideUrl || "");
  const [testing, setTesting] = React.useState(false);
  const [test, setTest] = React.useState(null);
  const [tab, setTab] = React.useState("settings");

  React.useEffect(() => { if (open) { const c = window.__api.getConfig(); setMode(c.mode); setEnvironment(c.environment); setOverrideUrl(c.overrideUrl || ""); setTest(null); setTab("settings"); } }, [open]);

  const envs = Object.entries(window.__api.environments);
  const effectiveUrl = overrideUrl.trim() || (window.__api.environments[environment]?.baseUrl) || "";

  const apply = async () => {
    await window.__api.setConfig({ mode, environment, overrideUrl: overrideUrl.trim() });
    window.__toast(mode === "live" ? `Switched to Live · ${environment}` : "Switched to Mock data");
    onClose();
  };
  const runTest = async () => {
    setTesting(true); setTest(null);
    // apply transiently so the test uses the chosen env/url
    await window.__api.setConfig({ mode, environment, overrideUrl: overrideUrl.trim() });
    const r = await window.__api.testConnection();
    setTest(r); setTesting(false);
  };

  return (
    <Modal open={open} onClose={onClose} title="API connection" width={560}
      footer={<><Btn kind="secondary" onClick={onClose}>Cancel</Btn><Btn kind="primary" onClick={apply}>Apply & reconnect</Btn></>}>
      <Tabs value={tab} onChange={setTab} items={[{ label: "Settings", value: "settings" }, { label: "Request log", value: "log" }]}/>

      {tab === "settings" ? (
        <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 4 }}>
          <FieldRow label="Data source" hint="Mock runs on bundled fixtures. Live calls the BFF endpoints." layout="stacked">
            <SegmentedControl value={mode} onChange={setMode} options={[{ label: "Mock data", value: "mock" }, { label: "Live API", value: "live" }]}/>
          </FieldRow>

          <FieldRow label="Environment" hint="Each maps to a BFF origin." layout="stacked">
            <div className="pw-env-pick">
              {envs.map(([name, e]) => (
                <button key={name} type="button" className={`pw-env-opt ${environment === name ? "on" : ""}`} onClick={() => setEnvironment(name)} disabled={mode !== "live"}>
                  <span className="pw-env-opt-name">{name}</span>
                  <span className="pw-env-opt-url">{e.baseUrl}</span>
                </button>
              ))}
            </div>
          </FieldRow>

          <FieldRow label="Base URL override" hint="Optional — point at a custom BFF (e.g. a local tunnel)." layout="stacked">
            <Input value={overrideUrl} onChange={e => setOverrideUrl(e.target.value)} placeholder={window.__api.environments[environment]?.baseUrl} disabled={mode !== "live"}/>
          </FieldRow>

          <div className="pw-conn-effective">
            <span style={{ color: "var(--muted)", fontSize: 12 }}>Endpoint</span>
            <code style={{ fontFamily: "var(--mono)", fontSize: 12.5 }}>{mode === "live" ? effectiveUrl : "— mock (no network) —"}</code>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 6 }}>
            <Btn kind="secondary" icon={<IconBolt size={14}/>} onClick={runTest} disabled={testing || mode !== "live"}>{testing ? "Testing…" : "Test connection"}</Btn>
            {test && (
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: test.ok ? "var(--good)" : "var(--bad)" }}>
                <span style={{ width: 7, height: 7, borderRadius: "50%", background: test.ok ? "var(--good)" : "var(--bad)" }}/>{test.detail}
              </span>
            )}
          </div>

          <Banner tone="info" icon={<IconInfo size={15}/>} style={{ marginTop: 12 }}>
            Switching reconnects and re-fetches every collection. Endpoints marked <em>to-add</em> in the API map have no backend yet and fall back to fixtures.
          </Banner>
        </div>
      ) : (
        <div style={{ marginTop: 16 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
            <span style={{ fontSize: 12.5, color: "var(--muted)" }}>Most recent first · live + mock calls</span>
            <Btn kind="ghost" size="sm" onClick={() => window.__api.clearLog()}>Clear</Btn>
          </div>
          <RequestLog/>
        </div>
      )}

      <style>{`
        .pw-env-pick { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; overflow: visible; max-height: none; }
        @media (max-width: 520px) { .pw-env-pick { grid-template-columns: 1fr; } }
        .pw-env-opt { display: flex; flex-direction: column; gap: 3px; align-items: flex-start; text-align: left; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r-md); background: var(--panel); cursor: pointer; font: inherit; }
        .pw-env-opt:hover:not(:disabled) { border-color: var(--accent); }
        .pw-env-opt.on { border-color: var(--accent); background: var(--accent-soft); }
        .pw-env-opt:disabled { opacity: .5; cursor: not-allowed; }
        .pw-env-opt-name { font-size: 13px; font-weight: 600; color: var(--ink); }
        .pw-env-opt-url { font-size: 11px; font-family: var(--mono); color: var(--muted); max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .pw-conn-effective { display: flex; align-items: center; gap: 10px; padding: 11px 13px; border: 1px solid var(--line-2); border-radius: var(--r-md); background: var(--panel-2); margin-top: 6px; }
        .pw-log { display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: var(--r-md); overflow: hidden; max-height: 320px; overflow-y: auto; }
        .pw-log-empty { padding: 32px 16px; text-align: center; color: var(--muted); font-size: 13px; border: 1px dashed var(--line); border-radius: var(--r-md); }
        .pw-log-row { display: grid; grid-template-columns: 52px 1fr auto auto; gap: 10px; align-items: center; padding: 8px 12px; border-bottom: 1px solid var(--line-2); font-size: 12px; }
        .pw-log-row:last-child { border-bottom: none; }
        .pw-log-method { font-family: var(--mono); font-weight: 600; font-size: 10.5px; }
        .pw-log-method.m-GET { color: var(--info-ink); }
        .pw-log-method.m-POST { color: var(--good); }
        .pw-log-method.m-PUT, .pw-log-method.m-PATCH { color: var(--warn); }
        .pw-log-method.m-DELETE { color: var(--bad); }
        .pw-log-url { font-family: var(--mono); color: var(--ink-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .pw-log-mode { font-size: 10px; text-transform: uppercase; letter-spacing: .04em; padding: 1px 6px; border-radius: 999px; background: var(--line-2); color: var(--muted); }
        .pw-log-mode.live { background: var(--good-soft); color: var(--good); }
        .pw-log-status { font-family: var(--mono); font-size: 11.5px; }
        .pw-log-status.ok { color: var(--good); }
        .pw-log-status.bad { color: var(--bad); }
      `}</style>
    </Modal>
  );
};

Object.assign(window, { ConnectionBadge, ConnectionModal, RequestLog });
