// ============================================================================
// public/screens/integrations.jsx — Integrations Manager (Phase 7B)
// ============================================================================

function IntegrationsScreen() {
  const [tab, setTab] = React.useState("apps"); // apps | webhooks
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <Tabs value={tab} onChange={setTab} options={[
        { value: "apps", label: "Integrations" }, { value: "webhooks", label: "Webhooks" },
      ]}/>
      {tab === "apps" && <IntegrationsTab/>}
      {tab === "webhooks" && <WebhooksTab/>}
    </div>
  );
}

function IntegrationsTab() {
  const [items, setItems] = React.useState(null);
  const load = () => VoaisAPI.get("/api/integrations").then(r => { if (r.ok) setItems(r.data.integrations); });
  React.useEffect(() => { load(); }, []);
  const toggle = async (key, connected) => {
    if (connected) await VoaisAPI.del("/api/integrations/" + key);
    else await VoaisAPI.post("/api/integrations/" + key, {});
    load();
  };
  if (!items) return <DashboardSkeleton/>;
  const cats = [...new Set(items.map(i => i.category))];
  return (<div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
    {cats.map(cat => (
      <div key={cat}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink-3)", marginBottom: 10 }}>{cat}</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 10 }}>
          {items.filter(i => i.category === cat).map(i => (
            <Card key={i.key}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--surface-2)", display: "grid", placeItems: "center" }}>
                  {I[i.icon] ? React.createElement(I[i.icon], { size: 18 }) : <I.link size={18}/>}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{i.name}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{i.description}</div>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12 }}>
                <Toggle value={i.connected} onChange={() => toggle(i.key, i.connected)}/>
                <span style={{ fontSize: 12, color: i.connected ? "var(--ok)" : "var(--ink-3)" }}>{i.connected ? "Connected" : "Not connected"}</span>
                {i.last_error && <span style={{ fontSize: 11, color: "var(--err)", marginLeft: "auto" }}>Error</span>}
              </div>
            </Card>
          ))}
        </div>
      </div>
    ))}
  </div>);
}

function WebhooksTab() {
  const [hooks, setHooks] = React.useState(null); const [showCreate, setShow] = React.useState(false);
  const load = () => VoaisAPI.get("/api/integrations/webhooks").then(r => { if (r.ok) setHooks(r.data.webhooks); });
  React.useEffect(() => { load(); }, []);
  const del = async (id) => { if (!confirm("Delete webhook?")) return; await VoaisAPI.del("/api/integrations/webhooks/" + id); load(); };
  if (!hooks) return <DashboardSkeleton/>;
  return (<div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <Badge tone="blue" dot>{hooks.length} webhooks</Badge><div style={{ flex: 1 }}/>
      <Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => setShow(true)}>Add webhook</Btn>
    </div>
    <Card padded={false}><table className="data-table" style={{width:"100%",fontSize:13}}>
      <thead><tr><th style={{paddingLeft:16}}>Name</th><th>URL</th><th>Events</th><th>Active</th><th></th></tr></thead>
      <tbody>{hooks.map(h => (
        <tr key={h.id}><td style={{paddingLeft:16,fontWeight:500}}>{h.name || "—"}</td>
        <td style={{fontSize:11,fontFamily:"var(--font-mono)",maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"}}>{h.url}</td>
        <td>{(h.events||[]).map(e => <Badge key={e} tone="gray">{e}</Badge>)}</td>
        <td><Badge tone={h.active ? "green" : "gray"}>{h.active ? "Active" : "Off"}</Badge></td>
        <td><Btn kind="ghost" size="sm" onClick={() => del(h.id)}><I.trash size={12}/></Btn></td></tr>
      ))}{hooks.length === 0 && <tr><td colSpan={5} style={{textAlign:"center",padding:32,color:"var(--ink-3)"}}>No webhooks configured.</td></tr>}</tbody>
    </table></Card>
    {showCreate && <Modal title="Add webhook" onClose={() => setShow(false)} width={460}><CreateWebhookForm onCreated={() => { setShow(false); load(); }}/></Modal>}
  </div>);
}

function CreateWebhookForm({ onCreated }) {
  const [name, setName] = React.useState(""); const [url, setUrl] = React.useState(""); const [events, setEvents] = React.useState("call.completed"); const [sub, setSub] = React.useState(false);
  const submit = async () => { if (!url.trim()) return; setSub(true); const r = await VoaisAPI.post("/api/integrations/webhooks", { name, url, events: events.split(",").map(s=>s.trim()) }); setSub(false); if (r.ok) { alert("Webhook secret: " + r.data.secret); onCreated(); } };
  return (<div style={{display:"flex",flexDirection:"column",gap:14}}>
    <Field label="Name"><input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. CRM sync"/></Field>
    <Field label="URL *"><input className="input" value={url} onChange={e => setUrl(e.target.value)} placeholder="https://your-server.com/webhook"/></Field>
    <Field label="Events" hint="Comma-separated: call.completed, lead.hot, campaign.ended"><input className="input" value={events} onChange={e => setEvents(e.target.value)}/></Field>
    <Btn kind="primary" onClick={submit} disabled={sub || !url.trim()}>{sub ? "Creating..." : "Create webhook"}</Btn>
  </div>);
}

window.IntegrationsScreen = IntegrationsScreen;
