// Account-level pages: Support (live API), Settings (live API)

const { useState: useStateO, useEffect: useEffectO } = React;

function SupportPage({ ctx }) {
  const { t } = ctx;
  const [tickets, setTickets] = useStateO([]);
  const [loading, setLoading] = useStateO(true);
  const [creating, setCreating] = useStateO(false);
  const [subject, setSubject] = useStateO("");
  const [body, setBody] = useStateO("");
  const [viewing, setViewing] = useStateO(null);
  const [messages, setMessages] = useStateO([]);
  const [replyBody, setReplyBody] = useStateO("");

  useEffectO(() => { loadTickets(); }, []);

  async function loadTickets() {
    try {
      const data = await ww.get("/tickets");
      setTickets(data);
    } catch {}
    setLoading(false);
  }

  async function handleCreate(e) {
    e.preventDefault();
    if (!subject.trim() || !body.trim()) return;
    try {
      await ww.post("/tickets", { subject: subject.trim(), body: body.trim() });
      setSubject(""); setBody(""); setCreating(false);
      loadTickets();
    } catch (err) { alert(err.message); }
  }

  async function openTicket(tk) {
    setViewing(tk);
    try {
      const data = await ww.get("/tickets/" + tk.id);
      setMessages(data.messages || []);
    } catch (err) { alert(err.message); }
  }

  async function handleReply() {
    if (!replyBody.trim() || !viewing) return;
    try {
      const msg = await ww.post("/tickets/" + viewing.id + "/reply", { body: replyBody.trim() });
      setMessages([...messages, msg]);
      setReplyBody("");
      loadTickets();
    } catch (err) { alert(err.message); }
  }

  function fmtDate(ts) {
    return new Date(ts * 1000).toISOString().slice(0, 10);
  }

  function fmtTime(ts) {
    return new Date(ts * 1000).toISOString().replace("T", " ").slice(0, 19);
  }

  if (viewing) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <Btn variant="ghost" small onClick={() => { setViewing(null); setMessages([]); setReplyBody(""); }}>← {t.common.back || "Back"}</Btn>
          <h1 style={{ fontSize: 20, fontWeight: 500, margin: 0, flex: 1 }}>{viewing.subject}</h1>
          <Pill tone={viewing.state === "open" ? "accent" : "ghost"} small>{viewing.state}</Pill>
        </div>
        <Card>
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {messages.map((msg, i) => (
              <div key={msg.id} style={{
                padding: "14px 0",
                borderTop: i > 0 ? "1px solid var(--line-2)" : "none",
              }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                  <span style={{ fontSize: 12, fontWeight: 500, color: msg.sender === "user" ? "var(--ink)" : "var(--accent)" }}>
                    {msg.sender === "user" ? (t.support.you || "You") : (t.support.supportTeam || "Support")}
                  </span>
                  <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{fmtTime(msg.created_at)}</span>
                </div>
                <div style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.6, whiteSpace: "pre-wrap" }}>{msg.body}</div>
              </div>
            ))}
            {messages.length === 0 && <div style={{ padding: 16, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>No messages.</div>}
          </div>
        </Card>
        {viewing.state === "open" && (
          <Card>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <div className="kicker" style={{ fontSize: 10 }}>{t.support.reply || "Reply"}</div>
              <textarea value={replyBody} onChange={e => setReplyBody(e.target.value)} rows={3} placeholder={t.support.replyPlaceholder || "Type your reply..."}
                style={{ width: "100%", fontFamily: "inherit", fontSize: 14, padding: "11px 13px", border: "1px solid var(--line)", borderRadius: 8, background: "var(--bg)", color: "var(--ink)", resize: "vertical" }}/>
              <div><Btn small onClick={handleReply}>{t.support.send || "Send"}</Btn></div>
            </div>
          </Card>
        )}
      </div>
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <h1 style={{ fontSize: 24, fontWeight: 500, margin: 0, letterSpacing: -0.01 }}>{t.nav.support}</h1>
        <Btn onClick={() => setCreating(!creating)}>{t.support.newTicket}</Btn>
      </div>

      {creating && (
        <Card>
          <form onSubmit={handleCreate} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div>
              <div className="kicker" style={{ fontSize: 10, marginBottom: 6 }}>{t.support.subject}</div>
              <input value={subject} onChange={e => setSubject(e.target.value)} placeholder="What's the issue?" autoFocus/>
            </div>
            <div>
              <div className="kicker" style={{ fontSize: 10, marginBottom: 6 }}>Description</div>
              <textarea value={body} onChange={e => setBody(e.target.value)} rows={4}
                style={{ width: "100%", fontFamily: "inherit", fontSize: 14, padding: "11px 13px", border: "1px solid var(--line)", borderRadius: 8, background: "var(--bg)", color: "var(--ink)", resize: "vertical" }}/>
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              <Btn type="submit">{t.common.save}</Btn>
              <Btn variant="ghost" onClick={() => setCreating(false)}>{t.common.cancel}</Btn>
            </div>
          </form>
        </Card>
      )}

      <Card pad={0}>
        <div className="ww-table" style={{ "--ww-cols": "1fr 3fr 1fr 1fr 24px" }}>
          <div className="ww-table__head">
            {[t.support.opened, t.support.subject, t.support.state, t.support.lastUpdate, ""].map((c, i) => <div key={i}>{c}</div>)}
          </div>
          {loading && <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>Loading...</div>}
          {!loading && tickets.length === 0 && (
            <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>No tickets.</div>
          )}
          {tickets.map((tk) => (
            <div key={tk.id} className="ww-table__row" onClick={() => openTicket(tk)} style={{ cursor: "pointer" }}>
              <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{fmtDate(tk.created_at)}</span>
              <span style={{ color: "var(--ink)" }}>{tk.subject}</span>
              <span><Pill tone={tk.state === "open" ? "accent" : "ghost"} small>{tk.state}</Pill></span>
              <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{fmtDate(tk.updated_at)}</span>
              <span style={{ fontSize: 14, color: "var(--ink-3)" }}>→</span>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function SettingsPage({ ctx }) {
  const { t } = ctx;
  const [profile, setProfile] = useStateO(null);
  const [tokens, setTokens] = useStateO([]);
  const [changingPw, setChangingPw] = useStateO(false);
  const [oldPw, setOldPw] = useStateO("");
  const [newPw, setNewPw] = useStateO("");
  const [pwMsg, setPwMsg] = useStateO("");
  const [mfaSetup, setMfaSetup] = useStateO(null);
  const [mfaCode, setMfaCode] = useStateO("");
  const [mfaMsg, setMfaMsg] = useStateO("");
  const [addingToken, setAddingToken] = useStateO(false);
  const [tokenForm, setTokenForm] = useStateO({ name: "", scope: "readonly", expires_days: "" });
  const [newTokenValue, setNewTokenValue] = useStateO("");

  useEffectO(() => {
    ww.get("/account").then(setProfile).catch(() => {});
    ww.get("/tokens").then(setTokens).catch(() => {});
  }, []);

  async function handleDeleteAccount() {
    if (!confirm(t.settings.deleteConfirm || "Are you sure? This cannot be undone.")) return;
    try {
      await ww.del("/account");
      ww.logout();
      window.location.href = "login.html";
    } catch (err) { alert(err.message); }
  }

  async function handleRevokeToken(id) {
    try {
      await ww.del("/tokens/" + id);
      setTokens(tokens.filter(tk => tk.id !== id));
    } catch (err) { alert(err.message); }
  }

  const email = profile ? profile.email : ME.email;
  const name = profile ? email.split("@")[0] : ME.name;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14, maxWidth: 820 }}>
      <h1 style={{ fontSize: 24, fontWeight: 500, margin: 0 }}>{t.settings.title}</h1>

      <Card title={t.settings.account}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div><div className="kicker" style={{ marginBottom: 6 }}>{t.settings.name}</div><input value={name} readOnly style={{ width: "100%", opacity: 0.7 }}/></div>
          <div><div className="kicker" style={{ marginBottom: 6 }}>{t.settings.email}</div><input value={email} readOnly style={{ width: "100%", opacity: 0.7 }}/></div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 0", borderTop: "1px solid var(--line-2)" }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{t.settings.mfa}</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 3 }}>
                {profile && profile.mfa_enabled ? t.settings.mfaOn : (t.settings.mfaOff || "Not configured")}
              </div>
            </div>
            {profile && profile.mfa_enabled ? (
              <Btn variant="ghost" small onClick={async () => {
                setMfaSetup("disable");
                setMfaCode("");
                setMfaMsg("");
              }}>{t.settings.disable || "Disable"}</Btn>
            ) : (
              <Btn variant="ghost" small onClick={async () => {
                try {
                  const res = await ww.post("/account/mfa/enable");
                  setMfaSetup(res);
                  setMfaCode("");
                  setMfaMsg("");
                } catch (e) { alert(e.message); }
              }}>{t.settings.configure}</Btn>
            )}
          </div>
          {mfaSetup === "disable" && (
            <div style={{ padding: "14px 0", borderTop: "1px solid var(--line-2)", display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Enter your current MFA code to disable two-factor authentication.</div>
              <input value={mfaCode} onChange={e => setMfaCode(e.target.value)} placeholder="6-digit code" style={{ width: 200, fontFamily: "var(--mono)" }}/>
              {mfaMsg && <div style={{ fontSize: 12, color: "var(--bad)" }}>{mfaMsg}</div>}
              <div style={{ display: "flex", gap: 8 }}>
                <Btn variant="danger" small onClick={async () => {
                  try {
                    await ww.post("/account/mfa/disable", { mfa_code: mfaCode });
                    setMfaSetup(null);
                    setProfile({ ...profile, mfa_enabled: false });
                  } catch (e) { setMfaMsg(e.message); }
                }}>{t.settings.disable || "Disable MFA"}</Btn>
                <Btn variant="ghost" small onClick={() => setMfaSetup(null)}>{t.common.cancel}</Btn>
              </div>
            </div>
          )}
          {mfaSetup && mfaSetup !== "disable" && (
            <div style={{ padding: "14px 0", borderTop: "1px solid var(--line-2)", display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Scan this URI with your authenticator app, or enter the secret manually:</div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 12, padding: "10px 14px", background: "var(--bg-2)", borderRadius: 6, wordBreak: "break-all" }}>{mfaSetup.secret}</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)" }}>OTP URI: {mfaSetup.otp_uri}</div>
              <div style={{ fontSize: 12, color: "var(--ink)", marginTop: 4 }}>MFA has been enabled. You will need your authenticator code on next login.</div>
              <Btn variant="ghost" small onClick={() => { setMfaSetup(null); setProfile({ ...profile, mfa_enabled: true }); }}>{t.common.close || "Done"}</Btn>
            </div>
          )}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 0", borderTop: "1px solid var(--line-2)" }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{t.settings.password}</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 3 }}>{t.settings.passwordHint}</div>
            </div>
            <Btn variant="ghost" small onClick={() => setChangingPw(!changingPw)}>{t.settings.changePassword}</Btn>
          </div>
          {changingPw && (
            <div style={{ padding: "14px 0", borderTop: "1px solid var(--line-2)", display: "flex", flexDirection: "column", gap: 10 }}>
              <input type="password" placeholder={t.settings.oldPw || "Current password"} value={oldPw} onChange={e => setOldPw(e.target.value)}/>
              <input type="password" placeholder={t.settings.newPw || "New password (8+ chars)"} value={newPw} onChange={e => setNewPw(e.target.value)}/>
              {pwMsg && <div style={{ fontSize: 12, color: pwMsg.startsWith("ok") ? "var(--accent)" : "var(--bad)" }}>{pwMsg}</div>}
              <div style={{ display: "flex", gap: 8 }}>
                <Btn small onClick={async () => {
                  try {
                    await ww.post("/account/password", { old_password: oldPw, new_password: newPw });
                    setPwMsg("ok"); setOldPw(""); setNewPw(""); setTimeout(() => { setChangingPw(false); setPwMsg(""); }, 1500);
                  } catch (e) { setPwMsg(e.message); }
                }}>{t.common.save}</Btn>
                <Btn variant="ghost" small onClick={() => { setChangingPw(false); setPwMsg(""); }}>{t.common.cancel}</Btn>
              </div>
            </div>
          )}
        </div>
      </Card>

      <Card title={t.settings.tokensTitle} action={<Btn small onClick={() => setAddingToken(!addingToken)}>+ {t.tokens.add}</Btn>} pad={0}>
        <div className="ww-table" style={{ "--ww-cols": "1fr 1.4fr 1.3fr 1fr 1fr 72px" }}>
          <div className="ww-table__help">{t.tokens.accountHint}</div>
          {addingToken && (
            <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line-2)", display: "grid", gridTemplateColumns: "1.5fr 1fr 1fr auto auto", gap: 10, alignItems: "end" }}>
              <div><div className="kicker" style={{ marginBottom: 4, fontSize: 10 }}>Name</div><input value={tokenForm.name} onChange={e => setTokenForm({...tokenForm, name: e.target.value})} placeholder="My token" style={{ width: "100%" }}/></div>
              <div><div className="kicker" style={{ marginBottom: 4, fontSize: 10 }}>Scope</div><select value={tokenForm.scope} onChange={e => setTokenForm({...tokenForm, scope: e.target.value})} style={{ width: "100%" }}><option value="readonly">readonly</option><option value="readwrite">readwrite</option><option value="admin">admin</option></select></div>
              <div><div className="kicker" style={{ marginBottom: 4, fontSize: 10 }}>Expires (days)</div><input type="number" min="1" value={tokenForm.expires_days} onChange={e => setTokenForm({...tokenForm, expires_days: e.target.value})} placeholder="never" style={{ width: "100%" }}/></div>
              <Btn variant="ghost" small onClick={() => setAddingToken(false)}>{t.common.cancel}</Btn>
              <Btn small onClick={async () => {
                if (!tokenForm.name.trim()) return;
                try {
                  const body = { name: tokenForm.name.trim(), scope: tokenForm.scope };
                  if (tokenForm.expires_days) body.expires_days = parseInt(tokenForm.expires_days);
                  const r = await ww.post("/tokens", body);
                  setNewTokenValue(r.token);
                  setTokens([r, ...tokens]);
                  setTokenForm({ name: "", scope: "readonly", expires_days: "" });
                  setAddingToken(false);
                } catch (e) { alert(e.message); }
              }}>{t.common.save}</Btn>
            </div>
          )}
          {newTokenValue && (
            <div style={{ padding: "12px 18px", background: "color-mix(in oklab, var(--accent) 8%, transparent)", borderBottom: "1px solid var(--line-2)", display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--mono)", fontSize: 12 }}>
              <span style={{ color: "var(--ink-3)" }}>New token:</span>
              <span style={{ flex: 1, wordBreak: "break-all" }}>{newTokenValue}</span>
              <Btn variant="ghost" small onClick={() => { navigator.clipboard.writeText(newTokenValue); }}>Copy</Btn>
              <Btn variant="ghost" small onClick={() => setNewTokenValue("")}>Dismiss</Btn>
            </div>
          )}
          <div className="ww-table__head">
            {[t.tokens.colName, t.tokens.colToken, t.tokens.colScopes, t.tokens.colCreated, t.tokens.colExpires, ""].map((c, i) => <div key={i}>{c}</div>)}
          </div>
          {tokens.length === 0 && !addingToken && (
            <div style={{ padding: 16, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>No API tokens.</div>
          )}
          {tokens.map((tk) => (
            <div key={tk.id} className="ww-table__row ww-table__row--mono ww-table__row--sm">
              <span style={{ fontWeight: 500 }}>{tk.name}</span>
              <span style={{ color: "var(--ink-3)" }}>{tk.token_prefix || "ww_***"}</span>
              <span>{tk.scope}</span>
              <span style={{ color: "var(--ink-3)" }}>{new Date(tk.created_at * 1000).toISOString().slice(0, 10)}</span>
              <span style={{ color: "var(--ink-3)" }}>{tk.expires_at ? new Date(tk.expires_at * 1000).toISOString().slice(0, 10) : "never"}</span>
              <span><Btn variant="ghost" small onClick={() => handleRevokeToken(tk.id)}>{t.tokens.revoke}</Btn></span>
            </div>
          ))}
        </div>
      </Card>

      <Card title={t.settings.dangerZone}>
        <p style={{ fontSize: 12, color: "var(--ink-3)", margin: "0 0 14px 0", lineHeight: 1.55 }}>{t.settings.deleteBody}</p>
        <Btn variant="danger" small onClick={handleDeleteAccount}>{t.settings.deleteMe}</Btn>
      </Card>
    </div>
  );
}

Object.assign(window, { SupportPage, SettingsPage });
