/* Tenant pages: dashboard, calls, insights, numbers, billing, team, connections, settings */
const formatCallDuration = (seconds) => {
  const total = Number(seconds || 0);
  if (!Number.isFinite(total) || total <= 0) return "0:00";
  const mins = Math.floor(total / 60);
  const secs = total % 60;
  return `${mins}:${String(secs).padStart(2, "0")}`;
};

const formatWhen = (iso) => {
  if (!iso) return "—";
  const diffMs = Date.now() - new Date(iso).getTime();
  if (!Number.isFinite(diffMs)) return "—";
  const mins = Math.floor(diffMs / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
};

const statusToOutcome = (status) => {
  if (!status) return "handled";
  if (status === "completed") return "handled";
  if (status === "failed") return "missed";
  if (status === "in_progress") return "live";
  return status;
};

const TenantDashboard = ({ onGo }) => {
  const store = MK_USE();
  const callTrend = [6,9,7,12,10,14,11,16,13,18,15,22,19,24];
  const toast = useToast();
  const recentCalls = (store.recentCalls || []).slice(0, 5);
  const completedCalls = (store.recentCalls || []).filter((c) => c.status === "completed").length;
  const escalatedCalls = (store.recentCalls || []).filter((c) => c.status === "failed").length;
  const mainNumber = store.tenantNumbers?.[0]?.phone_number || "No number assigned";
  return (
    <div className="page page-mount">
      <div className="page-header">
        <div>
          <div className="row gap-3" style={{ marginBottom: 8 }}>
            <Chip kind="live" dot>Your line is live</Chip>
            <span style={{ fontSize: 13, color: "var(--fg-muted)" }} className="mono">{mainNumber}</span>
          </div>
          <h1 className="page-title">Good morning, Ayo.</h1>
          <p className="page-sub">Mikaka handled <b style={{ color: "var(--fg)" }}>{completedCalls}</b> completed calls in your latest feed. <b style={{ color: "var(--fg)" }}>{escalatedCalls}</b> failed calls need review.</p>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline" onClick={() => { toast({ title: "Test call starting", body: "Your phone will ring in a moment." }); onGo("ai-receptionist"); }}><Icon name="play"/> Test call</button>
          <button className="btn btn-accent" onClick={() => onGo("ai-receptionist")}>
            Train receptionist <Icon name="arrow-right"/>
          </button>
        </div>
      </div>

      <div className="grid grid-4 stagger" style={{ marginBottom: 28 }}>
        <StatCard k="Calls in feed" v={String((store.recentCalls || []).length)} delta="live backend" up spark={<Spark data={callTrend}/>}/>
        <StatCard k="Avg handle time" v={recentCalls.length ? formatCallDuration(Math.round(recentCalls.reduce((s, c) => s + Number(c.duration_seconds || 0), 0) / recentCalls.length)) : "0:00"} delta="computed from calls" up/>
        <StatCard k="Completed" v={String(completedCalls)} delta="latest records" up/>
        <StatCard k="Failed / missed" v={String(escalatedCalls)} delta="needs follow-up" up={false}/>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "2fr 1fr", gap: 20 }}>
        <div className="card">
          <div className="row between" style={{ padding: "18px 20px", borderBottom: "1px solid var(--border)" }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 500 }}>Recent calls</div>
              <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Transcripts stream in real time</div>
            </div>
            <div className="row gap-2">
              <div className="seg"><button className="on">All</button></div>
              <a className="dot-link" style={{ fontSize: 13 }} onClick={() => onGo("tenant-calls")}>View all</a>
            </div>
          </div>
          <table className="tbl">
            <thead><tr><th>Caller</th><th>Intent</th><th>Outcome</th><th>Duration</th><th>Time</th></tr></thead>
            <tbody>
              {recentCalls.length === 0 ? (
                <tr><td colSpan={5} style={{ color: "var(--fg-muted)", textAlign: "center", padding: 28 }}>No calls yet.</td></tr>
              ) : recentCalls.map((r) => {
                const outcome = statusToOutcome(r.status);
                return (
                  <tr key={r.id} style={{ cursor: "pointer" }} onClick={() => onGo("call-detail")}>
                    <td><div className="row gap-2">{r.status === "in_progress" && <span className="live-dot"/>}<span className="mono cell-strong">{r.caller_number || "Unknown"}</span></div></td>
                    <td>{r.transcript_summary || "General enquiry"}</td>
                    <td><Chip kind={outcome === "completed" || outcome === "handled" ? "live" : outcome === "failed" || outcome === "missed" ? "warn" : "accent"} dot>{outcome}</Chip></td>
                    <td className="mono">{formatCallDuration(r.duration_seconds)}</td>
                    <td style={{ color: "var(--fg-muted)" }}>{formatWhen(r.created_at)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div className="stack gap-4">
          <div className="card card-pad">
            <div className="row between" style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Callbacks for you</div>
              <Chip kind="warn">2 waiting</Chip>
            </div>
            <div className="stack gap-3">
              {[
                { who: "Joyce N.", why: "Wants implant quote", age: "42m" },
                { who: "Peter O.", why: "Emergency — pain", age: "1h 12m" },
              ].map((c, i) => (
                <div key={i} className="row gap-3" style={{ padding: 10, background: "var(--bg-sunken)", borderRadius: 10 }}>
                  <div className="avatar" style={{ width: 34, height: 34, fontSize: 12 }}>{c.who.split(" ").map(s => s[0]).join("")}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 500 }}>{c.who}</div>
                    <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>{c.why} · {c.age}</div>
                  </div>
                  <button className="btn btn-ghost btn-icon btn-sm" onClick={() => toast({ title: "Calling " + c.who.split(" ")[0] + "…" })}><Icon name="phone" size={14}/></button>
                </div>
              ))}
            </div>
          </div>

          <div className="card card-pad">
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 14 }}>Quick tune-ups</div>
            <div className="stack gap-2">
              {[
                { t: "Update holiday hours", go: "tenant-settings" },
                { t: "Add M-Pesa collection", go: "connections" },
                { t: "Record a custom greeting", go: "ai-receptionist" },
              ].map((x, i) => (
                <a key={i} onClick={() => onGo(x.go)} className="row between" style={{ padding: "10px 12px", borderRadius: 8, fontSize: 13.5, cursor: "pointer", background: i === 0 ? "var(--accent-soft)" : "transparent" }}>
                  <span className="row gap-2"><Icon name="zap" size={14} style={{ color: "var(--mk-orange)" }}/> {x.t}</span>
                  <Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/>
                </a>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const TenantCalls = ({ onGo }) => {
  const [range, setRange] = useState("Today");
  const [calls, setCalls] = useState([]);
  useEffect(() => {
    let alive = true;
    api.calls.list({ page: 1, page_size: 100 }).then((rows) => {
      if (!alive) return;
      setCalls(rows || []);
    }).catch(() => {
      if (!alive) return;
      setCalls([]);
    });
    return () => { alive = false; };
  }, [range]);
  return (
  <div className="page page-mount">
    <div className="page-header">
      <div><h1 className="page-title">Calls</h1><p className="page-sub">All inbound and outbound, transcribed.</p></div>
      <div className="row gap-2">
        <button className="btn btn-outline"><Icon name="filter"/> Filter</button>
        <button className="btn btn-outline"><Icon name="download"/> Export CSV</button>
      </div>
    </div>
    <div className="row gap-3" style={{ marginBottom: 20, flexWrap: "wrap" }}>
      <div className="seg">{["Today","7 days","30 days","Custom"].map(r => <button key={r} className={range===r?"on":""} onClick={() => setRange(r)}>{r}</button>)}</div>
      <div className="chip">Intent: any <Icon name="chevron-down" size={12}/></div>
      <div className="chip">Outcome: any <Icon name="chevron-down" size={12}/></div>
      <div className="chip">Sentiment: any <Icon name="chevron-down" size={12}/></div>
    </div>
    <div className="card">
      <table className="tbl">
        <thead><tr><th>Caller</th><th>Intent</th><th>Outcome</th><th>Sentiment</th><th>Duration</th><th>Time</th><th></th></tr></thead>
        <tbody>
          {calls.length === 0 ? (
            <tr><td colSpan={7} style={{ color: "var(--fg-muted)", textAlign: "center", padding: 28 }}>No call records found.</td></tr>
          ) : calls.map((r) => {
            const outcome = statusToOutcome(r.status);
            return (
              <tr key={r.id} style={{ cursor: "pointer" }} onClick={() => onGo("call-detail")}>
                <td><div className="row gap-2">{r.status === "in_progress" && <span className="live-dot"/>}<span className="mono cell-strong">{r.caller_number || "Unknown"}</span></div></td>
                <td>{r.transcript_summary || "General enquiry"}</td>
                <td><Chip kind={outcome === "handled" ? "live" : outcome === "missed" ? "warn" : "accent"} dot>{outcome}</Chip></td>
                <td><span style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>{r.sentiment || "n/a"}</span></td>
                <td className="mono">{formatCallDuration(r.duration_seconds)}</td>
                <td style={{ color: "var(--fg-muted)" }}>{formatWhen(r.created_at)}</td>
                <td><Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  </div>
  );
};

const TenantInsights = () => {
  const [range, setRange] = useState("30d");
  return (
  <div className="page page-mount">
    <div className="page-header">
      <div><h1 className="page-title">Insights</h1><p className="page-sub">Trends, intents and quality across your calls.</p></div>
      <div className="seg">{["7d","30d","90d"].map(r => <button key={r} className={range===r?"on":""} onClick={() => setRange(r)}>{r}</button>)}</div>
    </div>
    <div className="grid grid-4 stagger" style={{ marginBottom: 24 }}>
      <StatCard k="Total calls" v="1,204" delta="14% vs prior" up spark={<Spark/>}/>
      <StatCard k="Booking rate" v="62%" delta="3 pts" up/>
      <StatCard k="First-call resolution" v="88%" delta="1 pt" up/>
      <StatCard k="Escalation rate" v="9%" delta="-2 pts" up/>
    </div>
    <div className="grid" style={{ gridTemplateColumns: "2fr 1fr", gap: 20 }}>
      <div className="card card-pad">
        <div className="row between" style={{ marginBottom: 16 }}>
          <div><div style={{ fontSize: 15, fontWeight: 500 }}>Call volume</div><div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Hourly · today</div></div>
        </div>
        <div className="bars">
          {[12,8,4,2,2,6,14,22,34,42,38,28,32,40,36,26,30,22,18,10,8,6,4,3].slice(0,14).map((h, i) => (
            <div key={i} className="b" style={{ height: h * 3 + "px" }}/>
          ))}
        </div>
        <div className="row between" style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 8 }}>
          <span>9am</span><span>12pm</span><span>3pm</span><span>6pm</span><span>9pm</span>
        </div>
      </div>
      <div className="card card-pad">
        <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 16 }}>Top intents</div>
        <div className="stack gap-3">
          {[
            ["Book appointment", 44, "var(--mk-orange)"],
            ["Pricing question", 22, "var(--mk-purple)"],
            ["Hours & location", 15, "var(--mk-slate-500)"],
            ["Reschedule", 11, "var(--mk-slate-400)"],
            ["Complaint", 8, "var(--mk-danger)"],
          ].map(([n, p, c], i) => (
            <div key={i}>
              <div className="row between" style={{ fontSize: 13, marginBottom: 4 }}><span>{n}</span><span className="mono" style={{ color: "var(--fg-muted)" }}>{p}%</span></div>
              <div style={{ height: 6, background: "var(--bg-sunken)", borderRadius: 4 }}>
                <div style={{ width: p + "%", height: "100%", background: c, borderRadius: 4 }}/>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  </div>
  );
};

const TenantNumbers = () => {
  const [addNum, setAddNum] = useState(false);
  const [numbers, setNumbers] = useState([]);
  const toast = useToast();
  useEffect(() => {
    let alive = true;
    api.numbers.listForTenant().then((rows) => {
      if (!alive) return;
      setNumbers(rows || []);
    }).catch(() => {
      if (!alive) return;
      setNumbers([]);
    });
    return () => { alive = false; };
  }, []);
  return (
  <div className="page page-mount">
    <AddNumberModal open={addNum} onClose={() => setAddNum(false)}/>
    <div className="page-header">
      <div><h1 className="page-title">Numbers</h1><p className="page-sub">Local and toll-free numbers routed to Mikaka.</p></div>
      <button className="btn btn-accent" onClick={() => setAddNum(true)}><Icon name="plus"/> Add number</button>
    </div>
    <div className="card">
      <table className="tbl">
        <thead><tr><th>Number</th><th>Region</th><th>Status</th><th>Type</th><th>Monthly</th><th>Minutes used</th><th></th></tr></thead>
        <tbody>
          {numbers.length === 0 ? (
            <tr><td colSpan={7} style={{ color: "var(--fg-muted)", textAlign: "center", padding: 28 }}>No numbers found.</td></tr>
          ) : numbers.map((n) => (
            <tr key={n.id} style={{ cursor: "pointer" }} onClick={() => toast({ title: n.phone_number, body: "Number settings will open here." })}>
              <td className="mono cell-strong">{n.phone_number}</td>
              <td>{n.country_code || "—"}</td>
              <td><Chip kind={n.is_active ? "live" : "warn"} dot>{n.is_active ? "live" : "inactive"}</Chip></td>
              <td>{n.number_type || "Local"}</td>
              <td className="mono">{n.monthly_fee != null ? `KES ${n.monthly_fee}` : "—"}</td>
              <td><span className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{n.minutes_used != null ? String(n.minutes_used) : "—"}</span></td>
              <td><Icon name="chevron-right" size={14} style={{ color: "var(--fg-faint)" }}/></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
  );
};

const TenantBilling = () => {
  const store = MK_USE();
  const toast = useToast();
  const summary = store.billingSummary || {};
  const usedMinutes = summary.minutes_used || 0;
  const includedMinutes = summary.included_minutes || 0;
  const amountThisMonth = summary.current_amount || summary.monthly_spend || 0;
  const currentPlan = summary.plan_name || "Growth";
  const invoices = summary.invoices || [];
  return (
  <div className="page page-mount">
    <div className="page-header">
      <div><h1 className="page-title">Billing</h1><p className="page-sub">Plan, usage, invoices and payment method.</p></div>
      <button className="btn btn-outline" onClick={() => toast({ title: "Invoices bundle downloading…" })}><Icon name="download"/> Download invoices</button>
    </div>
    <div className="grid" style={{ gridTemplateColumns: "2fr 1fr", gap: 20, marginBottom: 20 }}>
      <div className="card card-pad">
        <div className="row between" style={{ marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Current plan</div>
            <div className="row gap-2" style={{ marginTop: 4 }}>
              <div className="display" style={{ fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em" }}>{currentPlan}</div>
              <Chip kind="accent">Annual</Chip>
            </div>
          </div>
          <button className="btn btn-outline btn-sm" onClick={() => toast({ title: "Plan picker opening" })}>Change plan</button>
        </div>
        <div className="hr" style={{ margin: "18px 0" }}/>
        <div className="grid grid-3">
          <div><div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-muted)", fontWeight: 600 }}>Minutes used</div><div className="num" style={{ fontSize: 22, marginTop: 4 }}>{usedMinutes}<span style={{ fontSize: 13, color: "var(--fg-muted)" }}> / {includedMinutes || "—"}</span></div></div>
          <div><div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-muted)", fontWeight: 600 }}>This month</div><div className="num" style={{ fontSize: 22, marginTop: 4 }}>KES {amountThisMonth}</div></div>
          <div><div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--fg-muted)", fontWeight: 600 }}>Renews</div><div className="num" style={{ fontSize: 22, marginTop: 4 }}>{summary.renews_on || "—"}</div></div>
        </div>
      </div>
      <div className="card card-pad">
        <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginBottom: 6 }}>Payment method</div>
        <div className="row gap-3" style={{ padding: 12, background: "var(--bg-sunken)", borderRadius: 10, marginBottom: 12 }}>
          <Icon name="card"/>
          <div><div className="mono" style={{ fontSize: 13 }}>Visa •••• 4411</div><div style={{ fontSize: 12, color: "var(--fg-muted)" }}>expires 07/28</div></div>
        </div>
        <button className="btn btn-outline btn-sm" style={{ width: "100%", justifyContent: "center" }} onClick={() => toast({ title: "Payment method update" })}>Update</button>
      </div>
    </div>
    <Section title="Invoices" action={<a className="dot-link" style={{ fontSize: 13 }}>All invoices</a>}>
      <div className="card">
        <table className="tbl">
          <thead><tr><th>Invoice</th><th>Period</th><th>Amount</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {invoices.length === 0 ? (
              <tr><td colSpan={5} style={{ color: "var(--fg-muted)", textAlign: "center", padding: 28 }}>No invoices yet.</td></tr>
            ) : invoices.map((r) => (
              <tr key={r.id || r.invoice_number}><td className="mono cell-strong">{r.invoice_number || r.id}</td><td>{r.period || "—"}</td><td className="mono">KES {r.amount_due || r.total || 0}</td><td><Chip kind={r.status === "paid" ? "live" : "warn"} dot>{r.status || "pending"}</Chip></td><td><a className="btn btn-ghost btn-sm" onClick={() => toast({ title: "Downloading " + (r.invoice_number || "invoice") })}><Icon name="download" size={14}/></a></td></tr>
            ))}
          </tbody>
        </table>
      </div>
    </Section>
  </div>
  );
};

const TenantTeam = () => {
  const [invite, setInvite] = useState(false);
  const store = MK_USE();
  const toast = useToast();
  return (
  <div className="page page-mount">
    <InviteMemberModal open={invite} onClose={() => setInvite(false)}/>
    <div className="page-header">
      <div><h1 className="page-title">Team</h1><p className="page-sub">Who can see calls and edit the receptionist.</p></div>
      <button className="btn btn-accent" onClick={() => setInvite(true)}><Icon name="plus"/> Invite</button>
    </div>
    <div className="card">
      <table className="tbl">
        <thead><tr><th>Person</th><th>Role</th><th>Last seen</th><th></th></tr></thead>
        <tbody>
          {store.team.map((m) => (
            <tr key={m.id}>
              <td>
                <div className="row gap-3">
                  <div className="avatar" style={{ width: 32, height: 32, fontSize: 11 }}>{m.name.split(" ").map(s=>s[0]).join("").slice(0,2).toUpperCase()}</div>
                  <div><div className="cell-strong">{m.name}</div><div style={{ fontSize: 12, color: "var(--fg-muted)" }}>{m.email}</div></div>
                </div>
              </td>
              <td><Chip kind={m.role==="Owner" ? "accent" : "neutral"}>{m.role}</Chip></td>
              <td style={{ color: "var(--fg-muted)" }}>{m.last}</td>
              <td>
                {m.role !== "Owner" ? (
                  <button className="btn btn-ghost btn-sm" onClick={async () => { await api.team.remove(m.id); toast({ title: m.name + " removed", kind: "danger" }); }}>Remove</button>
                ) : null}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
  );
};

const TenantConnections = () => {
  const store = MK_USE();
  const toast = useToast();
  const toggle = async (id, nextName, on) => {
    await api.connections.toggle(id);
    toast({ title: (on ? "Disconnected from " : "Connected to ") + nextName });
  };
  const iconFor = (i) => i;
  return (
  <div className="page page-mount">
    <div className="page-header">
      <div><h1 className="page-title">Connections</h1><p className="page-sub">Calendars, payments, CRMs and webhooks.</p></div>
    </div>
    <div className="grid grid-2 stagger">
      {store.connections.map((c) => (
        <div key={c.id} className="card card-pad">
          <div className="row between" style={{ marginBottom: 10 }}>
            <div className="row gap-3">
              <div style={{ width: 40, height: 40, borderRadius: 10, background: "var(--bg-sunken)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={iconFor(c.icon)}/></div>
              <div><div style={{ fontWeight: 500 }}>{c.name}</div>{c.acct && <div className="mono" style={{ fontSize: 12, color: "var(--fg-muted)" }}>{c.acct}</div>}</div>
            </div>
            {c.on
              ? <button className="btn btn-ghost btn-sm" onClick={() => toggle(c.id, c.name, c.on)}><Chip kind="live" dot>connected</Chip></button>
              : <button className="btn btn-primary btn-sm" onClick={() => toggle(c.id, c.name, c.on)}>Connect</button>}
          </div>
          <div style={{ fontSize: 13.5, color: "var(--fg-muted)" }}>{c.desc}</div>
        </div>
      ))}
    </div>
  </div>
  );
};

const SETTINGS_SECTIONS = ["General", "Branding", "Notifications", "Security", "Data & privacy", "Danger zone"];

const TenantSettings = () => {
  const [sec, setSec] = useState("General");
  return (
    <div className="page page-mount">
      <div className="page-header"><div><h1 className="page-title">Settings</h1><p className="page-sub">Workspace, branding, privacy & security.</p></div></div>
      <div className="grid" style={{ gridTemplateColumns: "220px 1fr", gap: 32 }}>
        <div className="stack gap-1" style={{ fontSize: 13.5 }}>
          {SETTINGS_SECTIONS.map(s => (
            <a key={s} onClick={() => setSec(s)} style={{ padding: "8px 12px", borderRadius: 6, background: sec===s?"var(--bg-sunken)":"transparent", fontWeight: sec===s?500:400, color: sec===s?"var(--fg)":"var(--fg-muted)", cursor:"pointer" }}>{s}</a>
          ))}
        </div>
        <div className="stack gap-5">
          {sec === "General" && <SettingsGeneral/>}
          {sec === "Branding" && <SettingsBranding/>}
          {sec === "Notifications" && <SettingsNotifications/>}
          {sec === "Security" && <SettingsSecurity/>}
          {sec === "Data & privacy" && <SettingsData/>}
          {sec === "Danger zone" && <SettingsDanger/>}
        </div>
      </div>
    </div>
  );
};

const SettingsGeneral = () => (
  <>
    <div className="card card-pad">
      <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Workspace</h3>
      <div className="stack gap-4">
        <div className="field"><label>Business name</label><input className="input" defaultValue="Acme Dentistry"/></div>
        <div className="grid grid-2">
          <div className="field"><label>Time zone</label><select className="input"><option>Africa/Nairobi (UTC+3)</option><option>Africa/Lagos (UTC+1)</option></select></div>
          <div className="field"><label>Default language</label><select className="input"><option>English</option><option>Swahili</option></select></div>
        </div>
      </div>
    </div>
    <div className="card card-pad">
      <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Business hours</h3>
      <div className="stack gap-3">
        {["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"].map((d, i) => (
          <div key={i} className="row gap-3">
            <div style={{ width: 120, fontSize: 13.5 }}>{d}</div>
            <div className={`switch ${i<6?"on":""}`}/>
            <input className="input" defaultValue={i<5?"8:00 am":i===5?"9:00 am":"closed"} style={{ maxWidth: 120 }}/>
            <span style={{ color: "var(--fg-muted)" }}>–</span>
            <input className="input" defaultValue={i<5?"6:00 pm":i===5?"1:00 pm":""} style={{ maxWidth: 120 }}/>
          </div>
        ))}
      </div>
    </div>
  </>
);

const SettingsBranding = () => (
  <div className="card card-pad">
    <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Branding</h3>
    <div className="stack gap-4">
      <div>
        <label style={{ fontSize: 12.5, color: "var(--fg-muted)", display: "block", marginBottom: 8 }}>Logo</label>
        <div className="row gap-3">
          <div style={{ width: 72, height: 72, borderRadius: 12, background: "var(--bg-sunken)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 24, fontWeight: 500 }}>AD</div>
          <div className="stack gap-1">
            <button className="btn btn-outline btn-sm" style={{ width: "fit-content" }}>Upload new</button>
            <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>PNG or SVG, 1MB max.</div>
          </div>
        </div>
      </div>
      <div className="field"><label>Brand colour</label>
        <div className="row gap-2">
          {["#F27621","#8B5CF6","#0EA5E9","#10B981","#111827"].map(c => (
            <div key={c} style={{ width: 34, height: 34, borderRadius: 10, background: c, cursor: "pointer", border: c==="#F27621" ? "2px solid var(--fg)" : "1px solid var(--border)" }}/>
          ))}
        </div>
      </div>
      <div className="field"><label>Caller ID name</label><input className="input" defaultValue="Acme Dentistry"/><div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 6 }}>Shown to recipients of outbound calls where supported.</div></div>
    </div>
  </div>
);

const SettingsNotifications = () => (
  <div className="card card-pad">
    <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Notifications</h3>
    <div className="stack gap-3">
      {[
        ["Escalated calls", "Call me immediately when a caller asks for a human.", true],
        ["Booking confirmations", "Summary email after every booking.", true],
        ["Daily digest", "7am rollup of yesterday's calls.", true],
        ["Trunk health", "Only notify when trunk degrades.", false],
        ["Low balance / minutes", "Alert at 80% usage.", true],
      ].map(([t, d, on], i) => (
        <div key={i} className="row between" style={{ padding: "14px 0", borderBottom: i < 4 ? "1px solid var(--border)" : "none" }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 500, fontSize: 14 }}>{t}</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginTop: 2 }}>{d}</div>
          </div>
          <div className={`switch ${on?"on":""}`}/>
        </div>
      ))}
    </div>
  </div>
);

const SettingsSecurity = () => (
  <>
    <div className="card card-pad">
      <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Sign-in</h3>
      <div className="stack gap-3">
        <div className="row between" style={{ padding: "10px 0" }}>
          <div><div style={{ fontWeight: 500, fontSize: 14 }}>Two-factor authentication</div><div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Time-based codes via authenticator app.</div></div>
          <Chip kind="live" dot>enabled</Chip>
        </div>
        <div className="row between" style={{ padding: "10px 0" }}>
          <div><div style={{ fontWeight: 500, fontSize: 14 }}>SSO (Google Workspace)</div><div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Let teammates sign in with your Google domain.</div></div>
          <button className="btn btn-outline btn-sm">Configure</button>
        </div>
        <div className="row between" style={{ padding: "10px 0" }}>
          <div><div style={{ fontWeight: 500, fontSize: 14 }}>Session length</div><div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>How long sessions last before requiring re-auth.</div></div>
          <select className="input" style={{ maxWidth: 160 }}><option>7 days</option><option>30 days</option><option>90 days</option></select>
        </div>
      </div>
    </div>
    <div className="card card-pad">
      <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Active sessions</h3>
      <div className="stack gap-2">
        {[["MacBook · Chrome","Nairobi, KE","now","current"],["iPhone · Safari","Nairobi, KE","2h ago",""],["Windows · Edge","Mombasa, KE","3 days ago",""]].map(([d, l, w, tag], i) => (
          <div key={i} className="row between" style={{ padding: 10, background: "var(--bg-sunken)", borderRadius: 8 }}>
            <div><div style={{ fontSize: 13.5, fontWeight: 500 }}>{d}</div><div style={{ fontSize: 12, color: "var(--fg-muted)" }}>{l} · {w}</div></div>
            {tag ? <Chip kind="accent">this device</Chip> : <button className="btn btn-ghost btn-sm">Sign out</button>}
          </div>
        ))}
      </div>
    </div>
  </>
);

const SettingsData = () => (
  <>
    <div className="card card-pad">
      <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Retention</h3>
      <div className="stack gap-3">
        <div className="row between"><div><div style={{ fontWeight: 500, fontSize: 14 }}>Call recordings</div><div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Audio files auto-deleted after this period.</div></div>
          <select className="input" style={{ maxWidth: 160 }}><option>30 days</option><option>90 days</option><option>1 year</option><option>Forever</option></select>
        </div>
        <div className="row between"><div><div style={{ fontWeight: 500, fontSize: 14 }}>Transcripts</div><div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Text kept for analytics.</div></div>
          <select className="input" style={{ maxWidth: 160 }}><option>1 year</option><option>2 years</option><option>Forever</option></select>
        </div>
      </div>
    </div>
    <div className="card card-pad">
      <h3 style={{ margin: "0 0 16px", fontSize: 15, fontWeight: 500 }}>Export</h3>
      <p style={{ fontSize: 13.5, color: "var(--fg-muted)", marginBottom: 14 }}>Download all call data, transcripts and contacts as a ZIP.</p>
      <button className="btn btn-outline btn-sm">Request export</button>
    </div>
  </>
);

const SettingsDanger = () => {
  const toast = useToast();
  const [confirm, setConfirm] = useState("");
  return (
    <div className="card card-pad" style={{ borderColor: "var(--mk-danger)" }}>
      <h3 style={{ margin: "0 0 8px", fontSize: 15, fontWeight: 500, color: "var(--mk-danger)" }}>Delete workspace</h3>
      <p style={{ fontSize: 13.5, color: "var(--fg-muted)", marginBottom: 14 }}>This will release all numbers, delete recordings and transcripts, and cancel your subscription. This cannot be undone.</p>
      <div className="field"><label>Type <b>DELETE</b> to confirm</label><input className="input" value={confirm} onChange={e => setConfirm(e.target.value)}/></div>
      <button className="btn btn-sm" style={{ background: "var(--mk-danger)", color: "#fff", border: 0, marginTop: 12 }} disabled={confirm !== "DELETE"} onClick={() => toast({ title: "Workspace deletion scheduled", body: "You have 30 days to reverse this.", kind: "danger" })}>Delete workspace</button>
    </div>
  );
};

Object.assign(window, { TenantDashboard, TenantCalls, TenantInsights, TenantNumbers, TenantBilling, TenantTeam, TenantConnections, TenantSettings });
