/* ============================================================
   page-support.jsx — Support ticket management tab  ?v=8 (vpsie connect modal)
   ============================================================ */

(function () {
  const { useState, useEffect, useCallback, useRef } = React;
  const parseDetail = async (url, opts) => {
    const r = await fetch(url, { credentials: 'include', ...opts });
    if (!r.ok) throw new Error(r.status);
    return r.json();
  };

  /* ── helpers ─────────────────────────────────────── */
  function fmtDate(iso) {
    if (!iso) return '—';
    const d = new Date(iso);
    return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  }
  function fmtRelative(iso) {
    if (!iso) return '';
    const diff = Date.now() - new Date(iso).getTime();
    const s = Math.floor(diff / 1000);
    /* future timestamps or <60s → "just now" */
    const ar = window.appLang && window.appLang() === 'ar';
    if (s < 60) return ar ? 'الآن' : 'just now';
    const m = Math.floor(s / 60);
    if (m < 60) return ar ? `قبل ${m} د` : `${m}m ago`;
    const h = Math.floor(m / 60);
    if (h < 24) return ar ? `قبل ${h} س` : `${h}h ago`;
    return ar ? `قبل ${Math.floor(h / 24)} ي` : `${Math.floor(h / 24)}d ago`;
  }
  function fmtMin(min) {
    if (min == null) return '—';
    if (min < 60) return `${Math.round(min)}m`;
    return `${(min / 60).toFixed(1)}h`;
  }
  function initials(name) {
    if (!name) return '?';
    return name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
  }

  /* ── avatar ──────────────────────────────────────── */
  function Avatar({ name, size = 28 }) {
    const colors = ['#6366f1','#8b5cf6','#ec4899','#0ea5e9','#10b981','#f59e0b'];
    const i = name ? name.charCodeAt(0) % colors.length : 0;
    return (
      <div style={{
        width: size, height: size, borderRadius: '50%',
        background: colors[i], color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: size * 0.38, fontWeight: 700, flexShrink: 0,
        userSelect: 'none',
      }}>{initials(name)}</div>
    );
  }

  /* ── severity pill ───────────────────────────────── */
  function SevPill({ sev }) {
    const T = window.appT || (s => s);
    const MAP = {
      low:    { bg: '#10b981', label: T('Low') },
      medium: { bg: '#f59e0b', label: T('Medium') },
      high:   { bg: '#ef4444', label: T('High') },
    };
    const { bg, label } = MAP[sev] || { bg: '#6b7280', label: sev || '—' };
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center',
        padding: '3px 10px', borderRadius: 99,
        fontSize: 11, fontWeight: 700, color: '#fff',
        background: bg, letterSpacing: '0.04em',
        textTransform: 'uppercase',
      }}>{label}</span>
    );
  }

  /* ── status pill ─────────────────────────────────── */
  function StatusPill({ st }) {
    const T = window.appT || (s => s);
    const MAP = {
      open:         { bg: '#6b7280', label: T('Open') },
      acknowledged: { bg: '#3b82f6', label: T('Acknowledged') },
      in_progress:  { bg: '#f59e0b', label: T('In Progress') },
      resolved:     { bg: '#10b981', label: T('Resolved') },
      closed:       { bg: '#475569', label: T('Closed') },
    };
    const { bg, label } = MAP[st] || { bg: '#6b7280', label: st || '—' };
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center',
        padding: '3px 10px', borderRadius: 99,
        fontSize: 11, fontWeight: 700, color: '#fff',
        background: bg, letterSpacing: '0.04em',
      }}>{label}</span>
    );
  }

  /* ── toast ───────────────────────────────────────── */
  function Toast({ msg, type = 'ok', onDone }) {
    useEffect(() => {
      const t = setTimeout(onDone, 2800);
      return () => clearTimeout(t);
    }, []);
    const bg = type === 'err' ? '#ef4444' : '#10b981';
    return (
      <div style={{
        position: 'fixed', bottom: 24, right: 24, zIndex: 2000,
        background: bg, color: '#fff', borderRadius: 8,
        padding: '10px 18px', fontSize: 13, fontWeight: 500,
        boxShadow: '0 4px 16px rgba(0,0,0,0.3)',
        animation: 'fadein 0.2s ease',
      }}>{msg}</div>
    );
  }

  /* ── stats strip ─────────────────────────────────── */
  function StatsStrip({ stats }) {
    const st = stats || {};
    const noData = stats === null;
    const T = window.appT || (s => s);
    const items = [
      { label: T('Open'),              value: noData ? '—' : (st.open ?? 0),               accent: '#6b7280', topBar: '#6b7280' },
      { label: T('Acknowledged'),      value: noData ? '—' : (st.acknowledged ?? 0),       accent: '#3b82f6', topBar: '#3b82f6' },
      { label: T('Resolved this week'),value: noData ? '—' : (st.resolved_this_week ?? 0), accent: '#10b981', topBar: '#10b981' },
      { label: T('Avg response'),      value: fmtMin(st.avg_response_min),                 accent: st.avg_response_min != null ? 'var(--text-1)' : 'var(--text-3)', topBar: '#8b5cf6' },
    ];
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginBottom: 24 }}>
        {items.map(it => (
          <div
            key={it.label}
            className="support-stat-card"
            style={{
              background: 'var(--bg-elev-1)',
              border: '1px solid var(--line)',
              borderRadius: 12,
              padding: '18px 20px',
              position: 'relative',
              overflow: 'hidden',
              cursor: 'default',
              transition: 'transform 0.15s, box-shadow 0.15s',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.transform = 'translateY(-2px)';
              e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.25)';
            }}
            onMouseLeave={e => {
              e.currentTarget.style.transform = 'translateY(0)';
              e.currentTarget.style.boxShadow = 'none';
            }}
          >
            {/* top accent bar */}
            <div style={{
              position: 'absolute', top: 0, left: 0, right: 0, height: 3,
              background: it.topBar, borderRadius: '12px 12px 0 0',
            }} />
            <div style={{
              fontSize: 32, fontWeight: 700,
              color: it.accent,
              fontVariantNumeric: 'tabular-nums',
              lineHeight: 1.1,
              marginTop: 4,
            }}>{it.value}</div>
            <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 6, fontWeight: 500 }}>{it.label}</div>
          </div>
        ))}
      </div>
    );
  }

  /* ── severity segmented control ─────────────────── */
  function SevSegmented({ value, onChange }) {
    const T = window.appT || (s => s);
    const opts = [
      { value: 'low',    label: T('Low'),    bg: '#10b981' },
      { value: 'medium', label: T('Medium'), bg: '#f59e0b' },
      { value: 'high',   label: T('High'),   bg: '#ef4444' },
    ];
    return (
      <div style={{ display: 'flex', gap: 6 }}>
        {opts.map(o => (
          <button
            key={o.value}
            type="button"
            onClick={() => onChange(o.value)}
            style={{
              flex: 1,
              padding: '7px 12px',
              borderRadius: 8,
              border: value === o.value ? 'none' : '1px solid var(--line)',
              background: value === o.value ? o.bg : 'var(--bg-elev-2)',
              color: value === o.value ? '#fff' : 'var(--text-3)',
              fontSize: 12, fontWeight: 700,
              cursor: 'pointer',
              transition: 'all 0.15s',
              letterSpacing: '0.03em',
            }}
          >{o.label}</button>
        ))}
      </div>
    );
  }

  /* ── VPSie connect modal ─────────────────────────── */
  function VpsieConnectModal({ onClose, onConnected }) {
    const [clientId, setClientId] = useState('');
    const [clientSecret, setClientSecret] = useState('');
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState(null);

    async function submit(e) {
      e && e.preventDefault();
      const cid = clientId.trim(), sec = clientSecret.trim();
      const T = window.appT || (s => s);
      if (!cid || !sec) { setErr(T('Both Client ID and Client Secret are required.')); return; }
      setErr(null); setBusy(true);
      try {
        const r = await fetch('/api/me/vpsie/connect', {
          method: 'POST', credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ client_id: cid, client_secret: sec }),
        });
        if (!r.ok) {
          let msg = `HTTP ${r.status}`;
          try { const j = await r.json(); msg = j.detail || j.message || msg; } catch(_) {}
          setErr(typeof msg === 'string' ? msg : T('Could not validate those credentials.'));
          setBusy(false);
          return;
        }
        // Success — bust cache and notify parent
        await fetch('/api/me/vpsie/refresh', { method: 'POST', credentials: 'include' }).catch(()=>{});
        setBusy(false);
        onConnected && onConnected();
        onClose && onClose();
      } catch (_e) {
        setErr(T('Network error — please try again.'));
        setBusy(false);
      }
    }

    const overlay = {
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 9999,
    };
    const panel = {
      width: 'min(480px, 92vw)', background: 'var(--bg-elev-1)',
      border: '1px solid var(--line)', borderRadius: 12,
      padding: '22px 22px 18px', boxShadow: '0 24px 60px rgba(0,0,0,0.45)',
    };
    const inputStyle = {
      width: '100%', boxSizing: 'border-box', padding: '9px 12px',
      background: 'var(--bg-1)', border: '1px solid var(--line)',
      borderRadius: 6, color: 'var(--text-1)', fontSize: 13,
      fontFamily: 'var(--font-mono, monospace)',
    };
    const labelStyle = { display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 5 };

    return (
      <div style={overlay} onClick={(e) => { if (e.target === e.currentTarget && !busy) onClose && onClose(); }}>
        <div style={panel} role="dialog" aria-modal="true" aria-label="Connect VPSie">
          <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text-1)', marginBottom: 6 }}>
            {(window.appT||(s=>s))("Connect your VPSie account")}
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-3)', lineHeight: 1.5, marginBottom: 16 }}>
            {(window.appT||(s=>s))("Your client ID + secret are stored encrypted and only used to fetch")}
            <strong style={{ color: 'var(--text-2)' }}>{(window.appT||(s=>s))(" your ")}</strong>{(window.appT||(s=>s))("servers.")}
            {' '}{(window.appT||(s=>s))("Admins cannot see them. Generate creds at")}{' '}
            <a href="https://my.vpsie.com/account/api" target="_blank" rel="noopener noreferrer"
               style={{ color: 'var(--brand)' }}>my.vpsie.com/account/api</a>.
          </div>
          {err && (
            <div style={{ background: '#ef444420', border: '1px solid #ef4444', color: '#ef4444', borderRadius: 6, padding: '8px 12px', fontSize: 12, marginBottom: 12 }}>
              {err}
            </div>
          )}
          <form onSubmit={submit}>
            <div style={{ marginBottom: 12 }}>
              <label style={labelStyle}>{(window.appT||(s=>s))("Client ID")}</label>
              <input type="password" autoComplete="off" autoFocus
                style={inputStyle} value={clientId}
                onChange={e => setClientId(e.target.value)}
                placeholder={(window.appT||(s=>s))("vpsie client ID")} disabled={busy} />
            </div>
            <div style={{ marginBottom: 18 }}>
              <label style={labelStyle}>{(window.appT||(s=>s))("Client Secret")}</label>
              <input type="password" autoComplete="off"
                style={inputStyle} value={clientSecret}
                onChange={e => setClientSecret(e.target.value)}
                placeholder={(window.appT||(s=>s))("vpsie client secret")} disabled={busy} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
              <button type="button" onClick={onClose} disabled={busy}
                style={{ padding: '8px 16px', background: 'var(--bg-elev-2)', border: '1px solid var(--line)', borderRadius: 6, color: 'var(--text-2)', fontSize: 13, fontFamily: 'inherit', cursor: busy ? 'not-allowed' : 'pointer' }}>
                {(window.appT||(s=>s))("Cancel")}
              </button>
              <button type="submit" disabled={busy}
                style={{ padding: '8px 18px', background: 'var(--brand)', border: 'none', borderRadius: 6, color: '#fff', fontSize: 13, fontWeight: 600, fontFamily: 'inherit', cursor: busy ? 'not-allowed' : 'pointer', opacity: busy ? 0.7 : 1 }}>
                {busy ? (window.appT||(s=>s))('Validating…') : (window.appT||(s=>s))('Connect')}
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }

  /* ── new ticket form (VPSie-inspired layout) ─────── */
  function NewTicketForm({ onCreated }) {
    const [subject, setSubject]         = useState('');
    const [relatedServer, setRelatedSvr] = useState('');
    const [relatedSvrData, setRelatedSvrData] = useState(null);
    const [category, setCategory]       = useState('');
    const [severity, setSeverity]       = useState('medium');
    const [issue, setIssue]             = useState('');
    const [files, setFiles]             = useState([]);
    const [showVpsieModal, setShowVpsieModal] = useState(false);
    const [vpsieReloadKey, setVpsieReloadKey] = useState(0);
    const [vpsieToast, setVpsieToast] = useState(null);
    const [loading, setLoading]         = useState(false);
    const [err, setErr]                 = useState(null);
    const [ok,  setOk]                  = useState(null);
    const fileInputRef = useRef(null);

    function onFilesChange(e) {
      const picked = Array.from(e.target.files || []);
      // Cap individual file size and total selection at sensible limits
      const MAX_BYTES = 25 * 1024 * 1024;
      const valid = picked.filter(f => f.size <= MAX_BYTES);
      if (valid.length < picked.length) {
        setErr((window.appT||(s=>s))('One or more files exceed the 25 MB per-file limit.'));
      }
      setFiles(prev => [...prev, ...valid]);
      // Reset input so the same file can be re-selected if removed
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
    function removeFile(idx) {
      setFiles(prev => prev.filter((_, i) => i !== idx));
    }
    function fmtBytes(n) {
      if (n < 1024) return `${n} B`;
      if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
      return `${(n / (1024 * 1024)).toFixed(1)} MB`;
    }

    async function submit(e) {
      e.preventDefault();
      if (!issue.trim()) { setErr((window.appT||(s=>s))('Issue details are required.')); return; }
      setErr(null); setLoading(true);
      try {
        // Category value is "Label|@bot.matrix_id" — split it
        const [catLabel, assignedBot] = (category || '').split('|');
        // Compose backend payload — prepend subject + related-server context to issue body
        const composedIssue = [
          subject.trim() && `Subject: ${subject.trim()}`,
          relatedSvrData ? `Related server: hostname=${relatedSvrData.hostname}, ip=${relatedSvrData.ip}, status=${relatedSvrData.status}, region=${relatedSvrData.region}` : (relatedServer.trim() && `Related server: ${relatedServer.trim()}`),
          issue.trim(),
        ].filter(Boolean).join('\n\n');
        const res = await parseDetail('/api/support/escalate', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            team_name: catLabel || null,
            severity,
            issue: composedIssue,
            assigned_bot_matrix_id: assignedBot || null,
          }),
        });
        // Upload attachments (if any) — fire-and-forget; backend posts to room
        if (files.length > 0 && res?.id) {
          try {
            const fd = new FormData();
            files.forEach(f => fd.append('files', f, f.name));
            await fetch(`/api/support/tickets/${res.id}/attachments`, {
              method: 'POST', credentials: 'include', body: fd,
            });
          } catch (_e) { /* don't block ticket creation on attachment failure */ }
        }
        setOk(res.ticket_number);
        setSubject(''); setRelatedSvr(''); setRelatedSvrData(null); setCategory(''); setSeverity('medium'); setIssue(''); setFiles([]);
        onCreated && onCreated();
      } catch (_e) {
        setErr((window.appT||(s=>s))('Failed to create ticket. Please try again.'));
      } finally {
        setLoading(false);
      }
    }

    const fieldLabel = {
      position: 'absolute', top: -8, left: 12, padding: '0 6px',
      background: 'var(--bg-elev-1)', fontSize: 11, fontWeight: 600,
      color: 'var(--text-3)', letterSpacing: '0.04em', textTransform: 'uppercase',
      pointerEvents: 'none',
    };
    const fieldWrap = { position: 'relative', flex: 1 };
    const selectStyle = {
      width: '100%', boxSizing: 'border-box',
      appearance: 'none', WebkitAppearance: 'none',
      backgroundImage: 'url("data:image/svg+xml;charset=US-ASCII,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'10\' height=\'6\' viewBox=\'0 0 10 6\'%3E%3Cpath fill=\'%2394a3b8\' d=\'M0 0l5 6 5-6z\'/%3E%3C/svg%3E")',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'right 14px center',
      paddingRight: 36,
    };

    return (
      <React.Fragment>
      {showVpsieModal && (
        <VpsieConnectModal
          onClose={() => setShowVpsieModal(false)}
          onConnected={() => {
            setVpsieReloadKey(k => k + 1);
            setVpsieToast((window.appT||(s=>s))('VPSie connected. Server list refreshed.'));
            setTimeout(() => setVpsieToast(null), 4000);
          }}
        />
      )}
      <div style={{
        background: 'var(--bg-elev-1)',
        border: '1px solid var(--line)',
        borderRadius: 14, padding: '28px 28px 24px', marginBottom: 18,
      }}>
        {vpsieToast && (
          <div style={{ background: '#10b98120', border: '1px solid #10b981', borderRadius: 8, padding: '10px 14px', marginBottom: 16, fontSize: 13, color: '#10b981' }}>
            {vpsieToast}
          </div>
        )}
        {ok && (
          <div style={{ background: '#10b98120', border: '1px solid #10b981', borderRadius: 8, padding: '10px 14px', marginBottom: 16, fontSize: 13, color: '#10b981' }}>
            {(window.appT||(s=>s))("Ticket")} <strong>{ok}</strong> {(window.appT||(s=>s))("created and posted to the support room.")}
          </div>
        )}
        {err && (
          <div style={{ background: '#ef444420', border: '1px solid #ef4444', borderRadius: 8, padding: '10px 14px', marginBottom: 16, fontSize: 13, color: '#ef4444' }}>
            {err}
          </div>
        )}
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Row 1: Case Subject (full width) */}
          <div style={fieldWrap}>
            <span style={fieldLabel}>{(window.appT||(s=>s))("Case Subject")}</span>
            <input
              className="input support-input"
              style={{ width: '100%', boxSizing: 'border-box' }}
              value={subject} onChange={e => setSubject(e.target.value)}
              placeholder={(window.appT||(s=>s))("Briefly describe the issue")} />
          </div>

          {/* Row 2: Related Server | Category | Priority */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
            <div style={fieldWrap}>
              <span style={fieldLabel}>{(window.appT||(s=>s))("Related Server")}</span>
              <VPSieServerSelect
                value={relatedServer}
                reloadKey={vpsieReloadKey}
                onConnectClick={() => setShowVpsieModal(true)}
                onChange={id => {
                  // Store ID + find server data for context injection on submit
                  setRelatedSvr(id || '');
                  setRelatedSvrData(window.__vpsieServersCache ? window.__vpsieServersCache.find(s => String(s.id) === String(id)) : null);
                }}
                placeholder={(window.appT||(s=>s))("optional — select a VPSie server")}
              />
            </div>
            <div style={fieldWrap}>
              <span style={fieldLabel}>{(window.appT||(s=>s))("Category")}</span>
              <select
                className="input support-input"
                style={{ ...selectStyle, color: category ? 'var(--text-1)' : 'var(--text-3)' }}
                value={category} onChange={e => setCategory(e.target.value)}
              >
                <option value="">{(window.appT||(s=>s))("Select category…")}</option>
                {/* Each value is "Label|@bot.matrix_id" — backend splits to assign the right bot */}
                <option value="Technical|@tech.bot:k9.ms">{(window.appT||(s=>s))("Technical")}</option>
                <option value="DevOps / Infrastructure|@devops.bot:k9.ms">{(window.appT||(s=>s))("DevOps / Infrastructure")}</option>
                <option value="Security|@sec.bot:k9.ms">{(window.appT||(s=>s))("Security")}</option>
                <option value="HR|@hr.bot:k9.ms">{(window.appT||(s=>s))("HR")}</option>
                <option value="Finance|@fi.bot:k9.ms">{(window.appT||(s=>s))("Finance")}</option>
                <option value="Sales|@sales.bot:k9.ms">{(window.appT||(s=>s))("Sales")}</option>
                <option value="Customer Success|@cs.bot:k9.ms">{(window.appT||(s=>s))("Customer Success")}</option>
                <option value="Onboarding|@onboard.bot:k9.ms">{(window.appT||(s=>s))("Onboarding")}</option>
                <option value="Office|@office.bot:k9.ms">{(window.appT||(s=>s))("Office")}</option>
                <option value="Project / PM|@pm.bot:k9.ms">{(window.appT||(s=>s))("Project / PM")}</option>
                <option value="General Support|@support.bot:k9.ms">{(window.appT||(s=>s))("General Support")}</option>
              </select>
            </div>
            <div style={fieldWrap}>
              <span style={fieldLabel}>{(window.appT||(s=>s))("Priority")}</span>
              <SevSegmented value={severity} onChange={setSeverity} />
            </div>
          </div>

          {/* Row 3: Issue Details + helper */}
          <div style={fieldWrap}>
            <span style={fieldLabel}>{(window.appT||(s=>s))("Issue Details")}</span>
            <textarea
              className="input support-input"
              style={{ width: '100%', boxSizing: 'border-box', minHeight: 130, resize: 'vertical', fontFamily: 'inherit' }}
              value={issue} onChange={e => setIssue(e.target.value)}
              placeholder={(window.appT||(s=>s))("Describe the issue in detail…")} />
            <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 6, marginLeft: 2 }}>
              {(window.appT||(s=>s))("Describe the issue you have. The more details you add, the faster we'll be able to resolve it.")}
            </div>
          </div>

          {/* Row 4: Add Attachments (real file picker, multi-select) */}
          <div>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              onChange={onFilesChange}
              style={{ display: 'none' }}
            />
            <button
              type="button"
              onClick={() => fileInputRef.current && fileInputRef.current.click()}
              style={{
                display: 'flex', alignItems: 'center', gap: 10, width: '100%',
                padding: '14px 16px',
                background: 'var(--bg-1)',
                border: '1px dashed var(--border-1)',
                borderRadius: 8,
                color: 'var(--text-2)',
                fontSize: 13, fontWeight: 500,
                cursor: 'pointer',
                fontFamily: 'inherit',
                transition: 'border-color 120ms ease, background 120ms ease',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = '#10b981'; e.currentTarget.style.background = 'var(--bg-elev-2)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-1)'; e.currentTarget.style.background = 'var(--bg-1)'; }}
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48" />
              </svg>
              {(window.appT||(s=>s))("Add Attachments")}
              <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-3)' }}>
                {files.length > 0
                  ? (window.appLang && window.appLang() === 'ar'
                      ? `${files.length} ${files.length === 1 ? 'ملف' : 'ملفات'} محدد`
                      : `${files.length} file${files.length === 1 ? '' : 's'} selected`)
                  : (window.appT||(s=>s))('click to browse · 25 MB max each')}
              </span>
            </button>
            {files.length > 0 && (
              <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {files.map((f, i) => (
                  <div key={`${f.name}-${i}`} style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '8px 12px',
                    background: 'var(--bg-elev-2)',
                    border: '1px solid var(--line)',
                    borderRadius: 6,
                    fontSize: 12.5,
                  }}>
                    <span style={{ color: 'var(--text-3)' }}>📄</span>
                    <span style={{ color: 'var(--text-1)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</span>
                    <span style={{ color: 'var(--text-3)', fontSize: 11 }}>{fmtBytes(f.size)}</span>
                    <button
                      type="button"
                      onClick={() => removeFile(i)}
                      style={{
                        background: 'transparent', border: 'none', color: 'var(--text-3)',
                        cursor: 'pointer', fontSize: 16, lineHeight: 1, padding: '0 4px',
                      }}
                      title={(window.appT||(s=>s))("Remove")}
                    >×</button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Row 5: Create Support Case (full-width primary) */}
          <button
            type="submit"
            disabled={loading}
            style={{
              padding: '14px 16px',
              background: loading ? 'var(--bg-elev-2)' : '#1e3a8a',
              color: '#fff',
              border: 'none', borderRadius: 8,
              fontSize: 14, fontWeight: 600,
              cursor: loading ? 'wait' : 'pointer',
              transition: 'background 0.15s, transform 0.05s',
              fontFamily: 'inherit',
            }}
            onMouseEnter={e => { if (!loading) e.currentTarget.style.background = '#1e40af'; }}
            onMouseLeave={e => { if (!loading) e.currentTarget.style.background = '#1e3a8a'; }}
          >
            {loading ? (window.appT||(s=>s))('Creating Support Case…') : (window.appT||(s=>s))('Create Support Case')}
          </button>
        </form>
      </div>
      </React.Fragment>
    );
  }

  /* ── status filter segmented control ────────────── */
  function StatusFilterSeg({ value, onChange }) {
    const T = window.appT || (s => s);
    const opts = [
      { value: 'open',         label: T('Open') },
      { value: 'acknowledged', label: T('Acknowledged') },
      { value: 'in_progress',  label: T('In Progress') },
      { value: 'resolved',     label: T('Resolved') },
      { value: 'closed',       label: T('Closed') },
      { value: 'all',          label: T('All') },
    ];
    return (
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
        {opts.map(o => (
          <button
            key={o.value}
            type="button"
            onClick={() => onChange(o.value)}
            style={{
              padding: '5px 12px',
              borderRadius: 99,
              border: value === o.value ? 'none' : '1px solid var(--line)',
              background: value === o.value ? 'var(--brand)' : 'var(--bg-elev-2)',
              color: value === o.value ? '#fff' : 'var(--text-2)',
              fontSize: 12, fontWeight: 600,
              cursor: 'pointer',
              transition: 'all 0.12s',
            }}
          >{o.label}</button>
        ))}
      </div>
    );
  }

  /* ── assigned-to-me toggle pill ──────────────────── */
  function AssignedToggle({ value, onChange }) {
    return (
      <button
        type="button"
        onClick={() => onChange(!value)}
        style={{
          padding: '5px 14px',
          borderRadius: 99,
          border: value ? 'none' : '1px solid var(--line)',
          background: value ? '#10b981' : 'var(--bg-elev-2)',
          color: value ? '#fff' : 'var(--text-2)',
          fontSize: 12, fontWeight: 600,
          cursor: 'pointer',
          transition: 'all 0.12s',
          display: 'flex', alignItems: 'center', gap: 5,
        }}
      >
        {value && (
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12" />
          </svg>
        )}
        {(window.appT||(s=>s))("Assigned to me")}
      </button>
    );
  }

  /* ── ticket drawer ───────────────────────────────── */
  function TicketDrawer({ ticket, onClose, onUpdated }) {
    const [detail, setDetail] = useState(null);
    const [comment, setComment] = useState('');
    const [posting, setPosting] = useState(false);
    const [updating, setUpdating] = useState(false);
    const [toast, setToast] = useState(null);
    const drawerRef = useRef(null);

    /* load detail */
    useEffect(() => {
      parseDetail(`/api/support/tickets/${ticket.id}`)
        .then(setDetail)
        .catch(() => {});
    }, [ticket.id]);

    /* ESC to close */
    useEffect(() => {
      function onKey(e) { if (e.key === 'Escape') onClose(); }
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
    }, [onClose]);

    /* prevent body scroll when open */
    useEffect(() => {
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = ''; };
    }, []);

    const current = detail || ticket;

    async function patchStatus(newStatus) {
      setUpdating(true);
      try {
        await parseDetail(`/api/support/tickets/${ticket.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status: newStatus }),
        });
        onUpdated && onUpdated();
        const d = await parseDetail(`/api/support/tickets/${ticket.id}`);
        setDetail(d);
        const ar = window.appLang && window.appLang() === 'ar';
        const T = window.appT || (s => s);
        const stLabel = { open: T('Open'), acknowledged: T('Acknowledged'), in_progress: T('In Progress'), resolved: T('Resolved'), closed: T('Closed') }[newStatus] || newStatus.replace('_', ' ');
        setToast({ msg: ar ? `تم تحديث الحالة إلى ${stLabel}` : `Status updated to ${newStatus.replace('_', ' ')}`, type: 'ok' });
      } catch (_e) {
        setToast({ msg: (window.appT||(s=>s))('Failed to update status'), type: 'err' });
      } finally { setUpdating(false); }
    }

    async function postComment(e) {
      e.preventDefault();
      if (!comment.trim()) return;
      setPosting(true);
      try {
        await parseDetail(`/api/support/tickets/${ticket.id}/comment`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ body: comment.trim() }),
        });
        setComment('');
        const d = await parseDetail(`/api/support/tickets/${ticket.id}`);
        setDetail(d);
      } catch (_e) {
        setToast({ msg: (window.appT||(s=>s))('Failed to post comment'), type: 'err' });
      } finally { setPosting(false); }
    }

    /* action buttons config */
    const _T = window.appT || (s => s);
    const ACTION_BTNS = [
      { status: 'acknowledged', label: _T('Acknowledge'),      already: _T('Already acknowledged'),  bg: '#3b82f6' },
      { status: 'in_progress',  label: _T('Mark In Progress'), already: _T('Already in progress'),   bg: '#f59e0b' },
      { status: 'resolved',     label: _T('Resolve'),          already: _T('Already resolved'),      bg: '#10b981' },
      { status: 'closed',       label: _T('Close'),            already: _T('Already closed'),        bg: '#475569' },
    ];

    /* timeline entries */
    const _Tt = window.appT || (s => s);
    const timeline = [
      ticket.created_at && { ts: ticket.created_at, label: _Tt('Created'), by: ticket.submitted_by_name, color: '#6b7280' },
      current.acknowledged_at && { ts: current.acknowledged_at, label: _Tt('Acknowledged'), by: current.assigned_to_name, color: '#3b82f6' },
      current.resolved_at && { ts: current.resolved_at, label: _Tt('Resolved'), by: current.assigned_to_name, color: '#10b981' },
    ].filter(Boolean);

    const comments = detail?.comments || [];

    return (
      <div style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        display: 'flex', alignItems: 'stretch', justifyContent: 'flex-end',
      }}>
        {/* backdrop — deeper blur + higher opacity */}
        <div
          onClick={onClose}
          style={{
            position: 'absolute', inset: 0,
            background: 'rgba(0,0,0,0.75)',
            backdropFilter: 'blur(4px)',
            WebkitBackdropFilter: 'blur(4px)',
          }}
        />

        {/* panel */}
        <div
          ref={drawerRef}
          style={{
            position: 'relative',
            width: 'min(480px, 100vw)',
            height: '100%', overflowY: 'auto',
            background: 'var(--bg-base)',
            borderLeft: '1px solid var(--line)',
            boxShadow: '-12px 0 40px rgba(0,0,0,0.4)',
            display: 'flex', flexDirection: 'column',
            animation: 'slideInRight 0.2s ease',
          }}
        >
          {/* header bar */}
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '16px 24px',
            borderBottom: '1px solid var(--line)',
            background: 'var(--bg-elev-1)',
            flexShrink: 0,
            position: 'sticky', top: 0, zIndex: 10,
          }}>
            <span style={{ fontFamily: 'var(--font-mono,monospace)', fontSize: 13, fontWeight: 700, color: 'var(--brand)' }}>
              {ticket.ticket_number}
            </span>
            <button
              className="btn btn-ghost btn-icon"
              onClick={onClose}
              title={(window.appT||(s=>s))("Close (Esc)")}
              style={{ fontSize: 16, lineHeight: 1, padding: '4px 8px' }}
            >✕</button>
          </div>

          {/* scrollable body */}
          <div style={{ flex: 1, padding: '24px', display: 'flex', flexDirection: 'column', gap: 20 }}>

            {/* title + pills row */}
            <div>
              <div style={{ fontWeight: 700, fontSize: 16, color: 'var(--text-1)', marginBottom: 10 }}>
                {ticket.team_name || (window.appT||(s=>s))('Support Ticket')}
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
                <SevPill sev={ticket.severity} />
                <StatusPill st={current.status} />
                <button
                  className="btn btn-ghost"
                  style={{ marginLeft: 'auto', fontSize: 13, padding: '3px 10px' }}
                  onClick={() => {
                    parseDetail(`/api/support/tickets/${ticket.id}`)
                      .then(setDetail)
                      .catch(() => {});
                  }}
                  title={(window.appT||(s=>s))("Refresh")}
                >↻</button>
              </div>
            </div>

            {/* metadata grid */}
            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px 16px',
              background: 'var(--bg-elev-1)', border: '1px solid var(--line)',
              borderRadius: 10, padding: '16px',
            }}>
              <div>
                <div style={{ fontSize: 10.5, color: 'var(--text-3)', fontWeight: 600, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{(window.appT||(s=>s))("Submitted by")}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <Avatar name={ticket.submitted_by_name} size={24} />
                  <span style={{ fontSize: 13, color: 'var(--text-1)', fontWeight: 500 }}>{ticket.submitted_by_name || '—'}</span>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: 'var(--text-3)', fontWeight: 600, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{(window.appT||(s=>s))("Assigned to")}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  {current.assigned_to_name
                    ? <><Avatar name={current.assigned_to_name} size={24} /><span style={{ fontSize: 13, color: 'var(--text-1)', fontWeight: 500 }}>{current.assigned_to_name}</span></>
                    : <span style={{ fontSize: 13, color: 'var(--text-3)' }}>{(window.appT||(s=>s))("Unassigned")}</span>
                  }
                </div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: 'var(--text-3)', fontWeight: 600, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{(window.appT||(s=>s))("Created")}</div>
                <div style={{ fontSize: 13, color: 'var(--text-1)' }}>
                  {fmtDate(ticket.created_at)}
                  {ticket.created_at && <span style={{ color: 'var(--text-3)', marginLeft: 5 }}>({fmtRelative(ticket.created_at)})</span>}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: 'var(--text-3)', fontWeight: 600, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{(window.appT||(s=>s))("Last updated")}</div>
                <div style={{ fontSize: 13, color: 'var(--text-1)' }}>
                  {current.updated_at
                    ? <>{fmtDate(current.updated_at)} <span style={{ color: 'var(--text-3)' }}>({fmtRelative(current.updated_at)})</span></>
                    : '—'}
                </div>
              </div>
            </div>

            {/* issue card */}
            <div style={{
              border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden',
            }}>
              <div style={{
                padding: '10px 14px', background: 'var(--bg-elev-1)',
                borderBottom: '1px solid var(--line)',
                fontSize: 10.5, fontWeight: 700, color: 'var(--text-3)',
                textTransform: 'uppercase', letterSpacing: '0.07em',
              }}>{(window.appT||(s=>s))("Issue")}</div>
              <div style={{
                padding: '14px', fontSize: 13.5, color: 'var(--text-1)',
                lineHeight: 1.65, whiteSpace: 'pre-wrap',
                background: 'var(--bg-base)',
              }}>{ticket.issue}</div>
            </div>

            {/* resolution notes */}
            {detail?.resolution_notes && (
              <div style={{ border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
                <div style={{
                  padding: '10px 14px', background: 'var(--bg-elev-1)',
                  borderBottom: '1px solid var(--line)',
                  fontSize: 10.5, fontWeight: 700, color: 'var(--text-3)',
                  textTransform: 'uppercase', letterSpacing: '0.07em',
                }}>{(window.appT||(s=>s))("Resolution notes")}</div>
                <div style={{ padding: '14px', fontSize: 13, color: 'var(--text-1)', whiteSpace: 'pre-wrap' }}>
                  {detail.resolution_notes}
                </div>
              </div>
            )}

            {/* divider before actions */}
            <div style={{ borderTop: '1px solid var(--line)', marginTop: -4 }} />

            {/* action buttons */}
            <div>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 12 }}>{(window.appT||(s=>s))("Actions")}</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {ACTION_BTNS.map(a => {
                  const isCurrentStatus = a.status === current.status;
                  return (
                    <button
                      key={a.status}
                      onClick={() => !isCurrentStatus && patchStatus(a.status)}
                      disabled={updating || isCurrentStatus}
                      title={isCurrentStatus ? a.already : undefined}
                      style={{
                        padding: '7px 14px',
                        borderRadius: 8,
                        border: 'none',
                        cursor: isCurrentStatus || updating ? 'not-allowed' : 'pointer',
                        background: isCurrentStatus ? 'var(--bg-elev-2,#374151)' : a.bg,
                        color: isCurrentStatus ? 'var(--text-3)' : '#fff',
                        fontSize: 12.5,
                        fontWeight: 600,
                        opacity: updating ? 0.6 : 1,
                        transition: 'opacity 0.15s, transform 0.1s, filter 0.1s',
                      }}
                      onMouseEnter={e => { if (!isCurrentStatus && !updating) { e.currentTarget.style.filter = 'brightness(1.15)'; e.currentTarget.style.transform = 'scale(1.02)'; } }}
                      onMouseLeave={e => { e.currentTarget.style.filter = ''; e.currentTarget.style.transform = ''; }}
                    >
                      {isCurrentStatus ? a.already : a.label}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* status timeline */}
            {timeline.length > 0 && (
              <div>
                <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 12 }}>{(window.appT||(s=>s))("Timeline")}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                  {timeline.map((entry, idx) => (
                    <div key={idx} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', paddingBottom: 12 }}>
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                        <div style={{ width: 10, height: 10, borderRadius: '50%', background: entry.color, marginTop: 2 }} />
                        {idx < timeline.length - 1 && (
                          <div style={{ width: 2, flex: 1, background: 'var(--line)', marginTop: 2, minHeight: 20 }} />
                        )}
                      </div>
                      <div style={{ paddingBottom: 4 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-1)' }}>{entry.label}</span>
                        {entry.by && <span style={{ fontSize: 12, color: 'var(--text-3)', marginLeft: 6 }}>{(window.appT||(s=>s))("by")} {entry.by}</span>}
                        <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 2 }}>
                          {fmtDate(entry.ts)} · {fmtRelative(entry.ts)}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* comments */}
            <div>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 14 }}>
                {(window.appT||(s=>s))("Comments")} ({comments.length})
              </div>

              {/* empty comments state */}
              {comments.length === 0 && (
                <div style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center',
                  padding: '28px 16px', gap: 10, marginBottom: 16,
                  background: 'var(--bg-elev-1)', border: '1px solid var(--line)',
                  borderRadius: 10,
                }}>
                  {/* chat bubble icon */}
                  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" opacity="0.55">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                  </svg>
                  <div style={{ fontSize: 13, color: 'var(--text-3)', textAlign: 'center' }}>
                    {(window.appT||(s=>s))("No comments yet · be the first to add one")}
                  </div>
                </div>
              )}

              {comments.map(c => (
                <div key={c.id} style={{
                  marginBottom: 10,
                  background: 'var(--bg-elev-1)',
                  border: '1px solid var(--line)',
                  borderRadius: 10, padding: '12px 14px',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                    <Avatar name={c.author_name} size={24} />
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-1)' }}>{c.author_name}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-3)' }}>{fmtDate(c.created_at)} · {fmtRelative(c.created_at)}</div>
                    </div>
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--text-1)', whiteSpace: 'pre-wrap', lineHeight: 1.6 }}>{c.body}</div>
                </div>
              ))}

              <form onSubmit={postComment} style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
                <textarea
                  className="input support-input"
                  style={{ width: '100%', boxSizing: 'border-box', minHeight: 72, resize: 'vertical', fontFamily: 'inherit', fontSize: 13 }}
                  value={comment}
                  onChange={e => setComment(e.target.value)}
                  placeholder={(window.appT||(s=>s))("Add a comment…")}
                  onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) postComment(e); }}
                />
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <button className="btn btn-primary" type="submit" disabled={posting || !comment.trim()} style={{ fontSize: 12.5, padding: '6px 16px' }}>
                    {posting ? '…' : (window.appT||(s=>s))('Post comment')}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>

        {/* toast */}
        {toast && <Toast msg={toast.msg} type={toast.type} onDone={() => setToast(null)} />}
      </div>
    );
  }

  /* ── tickets table ───────────────────────────────── */
  function TicketsTable({ tickets, onSelect }) {
    const safeTickets = tickets || [];
    if (safeTickets.length === 0) {
      return (
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          padding: '56px 0', gap: 14,
        }}>
          {/* clipboard icon */}
          <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" opacity="0.45">
            <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />
            <rect x="8" y="2" width="8" height="4" rx="1" ry="1" />
          </svg>
          <div style={{ fontSize: 14, color: 'var(--text-3)', fontWeight: 500 }}>{(window.appT||(s=>s))("You currently don't have any support tickets.")}</div>
          <div style={{ fontSize: 12.5, color: 'var(--text-3)', opacity: 0.7 }}>{(window.appT||(s=>s))("Use the form above to create your first ticket.")}</div>
        </div>
      );
    }
    return (
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ borderBottom: '2px solid var(--line)', color: 'var(--text-3)', fontSize: 10.5 }}>
              {[(window.appT||(s=>s))('Ticket #'), (window.appT||(s=>s))('Team'), (window.appT||(s=>s))('Severity'), (window.appT||(s=>s))('Status'), (window.appT||(s=>s))('Submitted by'), (window.appT||(s=>s))('Created'), ''].map((h, hi) => (
                <th key={hi} style={{ padding: '10px 12px', textAlign: 'left', fontWeight: 700, whiteSpace: 'nowrap', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {safeTickets.map((t, idx) => (
              <tr
                key={t.id}
                style={{
                  borderBottom: '1px solid var(--line)',
                  cursor: 'pointer',
                  background: idx % 2 === 0 ? 'transparent' : 'rgba(255,255,255,0.015)',
                  transition: 'background 0.1s',
                }}
                onClick={() => onSelect(t)}
                onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}
                onMouseLeave={e => e.currentTarget.style.background = idx % 2 === 0 ? 'transparent' : 'rgba(255,255,255,0.015)'}
              >
                <td style={{ padding: '11px 12px', fontFamily: 'var(--font-mono,monospace)', fontSize: 12, color: 'var(--brand)', fontWeight: 500 }}>{t.ticket_number}</td>
                <td style={{ padding: '11px 12px', color: 'var(--text-2)' }}>{t.team_name || '—'}</td>
                <td style={{ padding: '11px 12px' }}><SevPill sev={t.severity} /></td>
                <td style={{ padding: '11px 12px' }}><StatusPill st={t.status} /></td>
                <td style={{ padding: '11px 12px', color: 'var(--text-2)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                    <Avatar name={t.submitted_by_name} size={22} />
                    {t.submitted_by_name || '—'}
                  </div>
                </td>
                <td style={{ padding: '11px 12px', color: 'var(--text-3)', whiteSpace: 'nowrap', fontSize: 12 }}>{fmtDate(t.created_at)}</td>
                <td style={{ padding: '11px 12px', textAlign: 'right' }}>
                  {/* ChevronRight icon instead of "View" button */}
                  <svg
                    width="16" height="16"
                    viewBox="0 0 24 24" fill="none"
                    stroke="var(--text-3)" strokeWidth="2.2"
                    strokeLinecap="round" strokeLinejoin="round"
                    style={{ display: 'block' }}
                  >
                    <polyline points="9 18 15 12 9 6" />
                  </svg>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  /* ── main SupportPage ────────────────────────────── */
  function SupportPage() {
    const [stats, setStats]           = useState(null);
    const [tickets, setTickets]       = useState([]);
    const [loading, setLoading]       = useState(true);
    const [filterStatus, setFilterStatus] = useState("all");
    const [filterTeam, setFilterTeam] = useState('');
    const [assignedMe, setAssignedMe] = useState(false);
    const [selected, setSelected]     = useState(null);

    const anyFilterActive = filterStatus !== 'all' || filterTeam !== '' || assignedMe;

    const reload = useCallback(async () => {
      setLoading(true);
      try {
        const params = new URLSearchParams();
        if (filterStatus !== 'all') params.set('status', filterStatus);
        if (filterTeam) params.set('team', filterTeam);
        if (assignedMe) params.set('assigned', 'me');
        params.set('limit', '50');
        const [s, t] = await Promise.all([
          parseDetail('/api/support/tickets/stats').catch(() => null),
          parseDetail('/api/support/tickets?' + params.toString()),
        ]);
        setStats(s);
        setTickets(Array.isArray(t) ? t : (t?.tickets ?? []));
      } catch (_e) {
        setTickets([]);
      } finally {
        setLoading(false);
      }
    }, [filterStatus, filterTeam, assignedMe]);

    useEffect(() => { reload(); }, [reload]);

    return (
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '28px 20px' }}>
        {/* styles */}
        <style>{`
          @keyframes slideInRight { from { transform: translateX(40px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
          @keyframes fadein { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
          .support-input {
            background: var(--bg-1) !important;
            color: var(--text-1) !important;
            border: 1px solid var(--border-1) !important;
            border-radius: 8px !important;
            padding: 10px 14px !important;
            font-size: 13.5px !important;
            font-family: inherit !important;
            line-height: 1.45 !important;
            transition: border-color 120ms ease, box-shadow 120ms ease;
            -webkit-text-fill-color: var(--text-1) !important;
          }
          .support-input:hover { border-color: var(--border-2) !important; }
          .support-input:focus {
            outline: none !important;
            border-color: #10b981 !important;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.18) !important;
          }
          .support-input::placeholder { color: var(--text-3) !important; opacity: 0.7 !important; }
          textarea.support-input { min-height: 96px; resize: vertical; }
          .support-input:-webkit-autofill,
          .support-input:-webkit-autofill:hover,
          .support-input:-webkit-autofill:focus {
            -webkit-text-fill-color: var(--text-1) !important;
            -webkit-box-shadow: 0 0 0 1000px var(--bg-1) inset !important;
            box-shadow: 0 0 0 1000px var(--bg-1) inset !important;
            caret-color: var(--text-1) !important;
          }
        `}</style>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 22, fontWeight: 800, color: 'var(--text-1)' }}>{(window.appT||(s=>s))("Support")}</h1>
            <div style={{ fontSize: 12.5, color: 'var(--text-3)', marginTop: 4 }}>{(window.appT||(s=>s))("Track and resolve escalated support tickets")}</div>
          </div>
          <button className="btn btn-ghost" onClick={reload} disabled={loading} title={(window.appT||(s=>s))("Refresh")} style={{ fontSize: 13 }}>
            {loading ? '…' : '↻ ' + (window.appT||(s=>s))('Refresh')}
          </button>
        </div>

        <StatsStrip stats={stats} />
        {/* Manual ticket/escalation form removed — tickets are ingested from the
            VPSie support room and escalation happens automatically up the
            on-call chain (primary → backup → escalation). */}

        {/* filters */}
        <div style={{
          display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap',
          marginBottom: 16, padding: '12px 16px',
          background: 'var(--bg-elev-1)', border: '1px solid var(--line)',
          borderRadius: 10,
        }}>
          <div style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', marginRight: 4 }}>{(window.appT||(s=>s))("Status")}</div>
          <StatusFilterSeg value={filterStatus} onChange={setFilterStatus} />

          <div style={{ width: 1, height: 22, background: 'var(--line)', margin: '0 4px', flexShrink: 0 }} />

          <input className="input support-input" style={{ fontSize: 12, padding: '5px 10px', minWidth: 130, maxWidth: 160 }}
            placeholder={(window.appT||(s=>s))("Team…")} value={filterTeam} onChange={e => setFilterTeam(e.target.value)} />

          <AssignedToggle value={assignedMe} onChange={setAssignedMe} />

          {/* clear filters */}
          {anyFilterActive && (
            <button
              type="button"
              onClick={() => { setFilterStatus('all'); setFilterTeam(''); setAssignedMe(false); }}
              style={{
                marginLeft: 'auto',
                padding: '5px 12px',
                borderRadius: 99,
                border: '1px solid var(--line)',
                background: 'transparent',
                color: 'var(--text-3)',
                fontSize: 12, fontWeight: 600,
                cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 5,
              }}
              title={(window.appT||(s=>s))("Clear all filters")}
            >
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round">
                <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
              </svg>
              {(window.appT||(s=>s))("Clear")}
            </button>
          )}
        </div>

        {/* Support Cases section header */}
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, margin: '6px 4px 14px' }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: 'var(--text-1)', letterSpacing: '0.01em' }}>
            {(window.appT||(s=>s))("Support Cases")}
          </h2>
          {!loading && tickets && (
            <span style={{ fontSize: 12, color: 'var(--text-3)' }}>
              {tickets.length} {tickets.length === 1 ? (window.appT||(s=>s))('case') : (window.appT||(s=>s))('cases')}
            </span>
          )}
        </div>
        {/* tickets table card */}
        <div style={{
          background: 'var(--bg-elev-1)', border: '1px solid var(--line)',
          borderRadius: 12, overflow: 'hidden',
        }}>
          {loading
            ? <div style={{ padding: '40px', textAlign: 'center', color: 'var(--text-3)', fontSize: 13 }}>{(window.appT||(s=>s))("Loading tickets…")}</div>
            : <TicketsTable tickets={tickets} onSelect={setSelected} />
          }
        </div>

        {selected && (
          <TicketDrawer
            ticket={selected}
            onClose={() => setSelected(null)}
            onUpdated={reload}
          />
        )}
      </div>
    );
  }

  window.SupportPage = SupportPage;
})();
