/* global React, I, S */
/* Pamp — Shared support page (client + vendor) with ticket creation */

function SupportPage({ kind = "client" }) {
  const [openNew, setOpenNew] = React.useState(false);
  const [openTicket, setOpenTicket] = React.useState(null);
  const [items, setItems] = React.useState(kind === "vendor" ? SAMPLE_VENDOR_TICKETS : SAMPLE_CLIENT_TICKETS);
  const [filter, setFilter] = React.useState("all");

  const counts = React.useMemo(() => ({
    all: items.length,
    open: items.filter(t => t.status === "Open").length,
    progress: items.filter(t => t.status === "In progress").length,
    resolved: items.filter(t => t.status === "Resolved").length,
  }), [items]);
  const filtered = filter === "all" ? items :
    filter === "open" ? items.filter(t => t.status === "Open") :
    filter === "progress" ? items.filter(t => t.status === "In progress") :
    items.filter(t => t.status === "Resolved");

  const addTicket = (payload) => {
    const id = "T-" + (8300 + items.length);
    setItems([{
      id, subject: payload.subject, body: payload.body,
      category: payload.category, priority: payload.priority,
      attachments: payload.attachments,
      status: "Open", updated: "just now", messages: 1, agent: "—",
    }, ...items]);
  };

  return (
    <div className="page-enter">
      <S.PageHead
        eyebrow={kind === "vendor" ? "Vendor support · 24/7" : "Help & support · 24/7"}
        title="Support"
        sub={kind === "vendor"
          ? "Talk to a specialist, browse guides, or open a ticket with the Pamp team."
          : "Open a ticket, browse the help center, or chat with us in real time."}
        right={<>
          <S.Btn variant="outline" size="sm" icon={<I.help size={14} />}>Help center</S.Btn>
          <S.Btn variant="primary" size="sm" icon={<I.plus size={14} />} onClick={() => setOpenNew(true)}>Open a ticket</S.Btn>
        </>}
      />

      {/* QUICK CONTACT CARDS */}
      <div className="grid-3" style={{ marginBottom: 24 }}>
        <ContactCard
          icon={<I.mail />} tone="accent"
          title="Live chat" hint="Median reply 4m 12s"
          meta={<><span className="dot dot-pos" /> 3 agents online</>}
          cta="Start chat"
        />
        <ContactCard
          icon={<I.help />}
          title="Help center" hint="182 guides · search anything"
          meta="Updated this week"
          cta="Browse guides"
        />
        <ContactCard
          icon={<I.phone />}
          title={kind === "vendor" ? "Talk to your CSM" : "Call us"}
          hint={kind === "vendor" ? "Dedicated to Atelier & Studio" : "Mon–Sun · 8am–10pm UTC"}
          meta={kind === "vendor" ? "Available now" : "+1 (415) 555 — PAMP"}
          cta="Book a call"
        />
      </div>

      {/* TICKETS LIST + RAIL */}
      <div style={{ display: "grid", gridTemplateColumns: openTicket ? "1fr 380px" : "1fr", gap: 20, alignItems: "flex-start" }}>
        <div className="card card-flush">
          <div className="row between" style={{ padding: "20px 22px 14px", borderBottom: "1px solid var(--border)" }}>
            <div>
              <div className="h3">My tickets</div>
              <div className="muted tiny" style={{ marginTop: 4 }}>Sent to the Pamp admin team — usually answered same day.</div>
            </div>
            <div className="row-tight" style={{ flexWrap: "wrap" }}>
              {[
                { k: "all", l: "All", n: counts.all },
                { k: "open", l: "Open", n: counts.open },
                { k: "progress", l: "In progress", n: counts.progress },
                { k: "resolved", l: "Resolved", n: counts.resolved },
              ].map(f => (
                <button key={f.k} onClick={() => setFilter(f.k)}
                  className={`btn btn-sm ${filter === f.k ? "btn-primary" : "btn-outline"}`}>
                  {f.l} <span className="mono tiny" style={{ marginLeft: 4, opacity: 0.7 }}>{f.n}</span>
                </button>
              ))}
            </div>
          </div>
          {filtered.length === 0 ? (
            <div style={{ padding: 60, textAlign: "center" }}>
              <div style={{
                width: 56, height: 56, borderRadius: 16, background: "var(--surface-3)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                color: "var(--ink-3)", marginBottom: 14,
              }}><I.inbox size={24} /></div>
              <div className="h3">Nothing here</div>
              <div className="muted" style={{ fontSize: 13, marginTop: 6 }}>You don’t have any tickets in this filter.</div>
            </div>
          ) : (
            <table className="tbl">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Subject</th>
                  <th>Category</th>
                  <th>Priority</th>
                  <th>Status</th>
                  <th>Updated</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {filtered.map(t => (
                  <tr key={t.id} onClick={() => setOpenTicket(t)} style={{ cursor: "pointer", background: openTicket?.id === t.id ? "var(--accent-soft)" : undefined }}>
                    <td className="mono muted">{t.id}</td>
                    <td>
                      <div style={{ fontWeight: 500 }}>{t.subject}</div>
                      <div className="muted tiny" style={{ maxWidth: 320, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.body}</div>
                    </td>
                    <td><S.Chip>{t.category}</S.Chip></td>
                    <td><S.Chip tone={t.priority === "Urgent" ? "neg" : t.priority === "Normal" ? "info" : "warn"}>{t.priority}</S.Chip></td>
                    <td><S.Chip tone={t.status === "Open" ? "warn" : t.status === "In progress" ? "info" : t.status === "Resolved" ? "pos" : ""}>{t.status}</S.Chip></td>
                    <td className="muted tiny">{t.updated}</td>
                    <td><S.IconBtn><I.chevR size={14} /></S.IconBtn></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {openTicket && <ClientTicketDetail t={openTicket} onClose={() => setOpenTicket(null)} />}
      </div>

      {/* POPULAR GUIDES */}
      <div className="card card-flush" style={{ marginTop: 24 }}>
        <div className="row between" style={{ padding: "20px 22px 14px", borderBottom: "1px solid var(--border)" }}>
          <div>
            <div className="h3">Popular guides</div>
            <div className="muted tiny" style={{ marginTop: 4 }}>The articles most people read this week.</div>
          </div>
          <S.Btn variant="ghost" size="sm" iconRight={<I.arrowR size={12} />}>All guides</S.Btn>
        </div>
        <div className="grid-3" style={{ gap: 0 }}>
          {(kind === "vendor" ? VENDOR_GUIDES : CLIENT_GUIDES).map((g, i) => (
            <div key={g.t} style={{
              padding: 22,
              borderRight: i % 3 !== 2 ? "1px solid var(--border)" : undefined,
              borderTop: i >= 3 ? "1px solid var(--border)" : undefined,
            }}>
              <span style={{ width: 32, height: 32, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}>
                {React.cloneElement(g.ic, { size: 16 })}
              </span>
              <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>{g.t}</div>
              <div className="muted tiny" style={{ lineHeight: 1.5 }}>{g.d}</div>
            </div>
          ))}
        </div>
      </div>

      <NewTicketModal open={openNew} onClose={() => setOpenNew(false)} onSubmit={addTicket} kind={kind} />
    </div>
  );
}

function ContactCard({ icon, title, hint, meta, cta, tone }) {
  return (
    <div className="card" style={{
      padding: 24, display: "flex", flexDirection: "column", gap: 14,
      background: tone === "accent" ? "var(--accent-soft)" : undefined,
      borderColor: tone === "accent" ? "transparent" : undefined,
      color: tone === "accent" ? "var(--accent-ink)" : undefined,
    }}>
      <span style={{
        width: 44, height: 44, borderRadius: 12,
        background: tone === "accent" ? "var(--accent)" : "var(--surface-3)",
        color: tone === "accent" ? "oklch(20% 0.10 145)" : "var(--ink)",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
      }}>{React.cloneElement(icon, { size: 20 })}</span>
      <div>
        <div className="display" style={{ fontSize: 22, letterSpacing: "-0.02em" }}>{title}</div>
        <div style={{ fontSize: 13, color: tone === "accent" ? "var(--accent-ink)" : "var(--ink-3)", marginTop: 4 }}>{hint}</div>
      </div>
      <div className="row between" style={{ marginTop: "auto", paddingTop: 8 }}>
        <span className="row-tight tiny" style={{ color: tone === "accent" ? "var(--accent-ink)" : "var(--ink-3)" }}>{meta}</span>
        <S.Btn variant={tone === "accent" ? "ink" : "outline"} size="sm" iconRight={<I.arrowR size={12} />}>{cta}</S.Btn>
      </div>
    </div>
  );
}

function ClientTicketDetail({ t, onClose }) {
  return (
    <div className="card" style={{ padding: 0, position: "sticky", top: 0 }}>
      <div style={{ padding: "20px 22px 18px", borderBottom: "1px solid var(--border)" }}>
        <div className="row between">
          <div className="eyebrow">{t.id} · {t.category}</div>
          <S.IconBtn onClick={onClose}><I.x size={14} /></S.IconBtn>
        </div>
        <div className="display" style={{ fontSize: 18, marginTop: 8, letterSpacing: "-0.015em", lineHeight: 1.3 }}>{t.subject}</div>
        <div className="row" style={{ marginTop: 12, gap: 6 }}>
          <S.Chip tone={t.priority === "Urgent" ? "neg" : t.priority === "Normal" ? "info" : "warn"}>{t.priority}</S.Chip>
          <S.Chip tone={t.status === "Open" ? "warn" : t.status === "In progress" ? "info" : "pos"}>{t.status}</S.Chip>
        </div>
      </div>

      <div style={{ padding: 22, borderBottom: "1px solid var(--border)" }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Assigned agent</div>
        {t.agent === "—" ? (
          <div className="row-tight">
            <div style={{ width: 36, height: 36, borderRadius: 999, background: "var(--surface-3)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}>
              <I.clock size={16} />
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Awaiting agent</div>
              <div className="muted tiny">Pamp team usually picks up within an hour.</div>
            </div>
          </div>
        ) : (
          <div className="row-tight">
            <S.Avatar name={t.agent} size="lg" />
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{t.agent}</div>
              <div className="muted tiny">Pamp support · usually replies same day</div>
            </div>
          </div>
        )}
      </div>

      <div style={{ padding: 22, borderBottom: "1px solid var(--border)" }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Thread · {t.messages} {t.messages === 1 ? "message" : "messages"}</div>
        <div className="col" style={{ gap: 10 }}>
          <div style={{ padding: 12, background: "var(--surface-2)", borderRadius: 10, fontSize: 13, lineHeight: 1.5 }}>
            <div className="row between" style={{ marginBottom: 6 }}>
              <span style={{ fontSize: 11.5, fontWeight: 500 }}>You</span>
              <span className="muted tiny">{t.updated}</span>
            </div>
            {t.body}
          </div>
          {t.replyFromAdmin && (
            <div style={{ padding: 12, background: "var(--accent-soft)", color: "var(--accent-ink)", borderRadius: 10, fontSize: 13, lineHeight: 1.5 }}>
              <div className="row between" style={{ marginBottom: 6 }}>
                <span style={{ fontSize: 11.5, fontWeight: 500 }}>{t.agent} · Pamp</span>
                <span className="muted tiny" style={{ color: "var(--accent-ink)", opacity: 0.7 }}>{t.replyTime}</span>
              </div>
              {t.replyFromAdmin}
            </div>
          )}
        </div>
      </div>

      <div style={{ padding: 22 }}>
        <textarea className="text-input" rows={4} placeholder="Add a reply or extra context…" />
        <div className="row" style={{ marginTop: 10, gap: 6 }}>
          <S.Btn variant="ghost" size="sm" icon={<I.export size={12} />}>Attach file</S.Btn>
          <div className="spacer" />
          <S.Btn variant="outline" size="sm">Mark resolved</S.Btn>
          <S.Btn variant="primary" size="sm" iconRight={<I.arrowR size={12} />}>Send</S.Btn>
        </div>
      </div>
    </div>
  );
}

function NewTicketModal({ open, onClose, onSubmit, kind }) {
  const initial = { subject: "", body: "", category: kind === "vendor" ? "Payouts" : "Bookings", priority: "Normal", attachments: 0 };
  const [data, setData] = React.useState(initial);
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const close = () => { onClose(); setData(initial); };
  const submit = () => { onSubmit(data); close(); };

  const categories = kind === "vendor"
    ? [
      { value: "Payouts", label: "Payouts & money", desc: "Missing payout, holding period, fees" },
      { value: "Bookings", label: "Bookings & calendar", desc: "Reschedules, cancellations, no-shows" },
      { value: "Account", label: "Account & access", desc: "Login, 2FA, staff seats" },
      { value: "Other", label: "Something else" },
    ]
    : [
      { value: "Bookings", label: "Bookings & appointments", desc: "Reschedules, cancellations, refunds" },
      { value: "Wallet", label: "Wallet & receipts", desc: "Top-ups, missing credit, statements" },
      { value: "Account", label: "Account & access", desc: "Login, 2FA, email change" },
      { value: "Other", label: "Something else" },
    ];

  return (
    <window.M.Modal open={open} onClose={close} size="lg"
      icon={<I.help />} title="Open a support ticket"
      subtitle="Send this to the Pamp admin team. We answer most tickets the same day."
      footer={<>
        <S.Btn variant="ghost" onClick={close}>Cancel</S.Btn>
        <S.Btn variant="outline">Save draft</S.Btn>
        <S.Btn variant="primary" iconRight={<I.arrowR size={14} />} onClick={submit} disabled={!data.subject || !data.body}>Send to admin</S.Btn>
      </>}
    >
      <window.M.FormGrid>
        <window.M.Field full label="Category">
          <window.M.RadioCards value={data.category} onChange={(v) => set("category", v)} options={categories} />
        </window.M.Field>

        <window.M.Field full label="Priority">
          <window.M.Segmented value={data.priority} onChange={(v) => set("priority", v)}
            options={[
              { value: "Low", label: "Low" },
              { value: "Normal", label: "Normal" },
              { value: "Urgent", label: "Urgent" },
            ]} />
        </window.M.Field>

        <window.M.Field full label="Subject" hint="Short and specific — like an email subject.">
          <window.M.TextField value={data.subject} onChange={(v) => set("subject", v)} placeholder="e.g. Can’t change my appointment for Saturday" />
        </window.M.Field>

        <window.M.Field full label="Describe the issue" hint="Include any IDs, dates, or screenshots — anything that helps us help you.">
          <window.M.Textarea value={data.body} onChange={(v) => set("body", v)} rows={6}
            placeholder={kind === "vendor"
              ? "We tried to invite Léa to the studio account but the email never arrived. Tried twice yesterday and once this morning…"
              : "I booked Forest Spa for tomorrow at 10am and want to move it to 2pm, but the reschedule button is greyed out…"} />
        </window.M.Field>

        <window.M.Field full label="Attachments (optional)">
          <window.M.FileDrop label="Drag & drop screenshots or click to upload" hint="PNG, JPG, or PDF · up to 12MB each" />
        </window.M.Field>

        <window.M.Field full>
          <div className="row-tight" style={{ padding: 14, background: "var(--accent-soft)", color: "var(--accent-ink)", borderRadius: 10, fontSize: 13 }}>
            <I.sparkle size={14} />
            We’ll email you when an agent picks this up. You can keep an eye on it from this page.
          </div>
        </window.M.Field>
      </window.M.FormGrid>
    </window.M.Modal>
  );
}

const SAMPLE_CLIENT_TICKETS = [
  {
    id: "T-8298", subject: "Refund for cancelled appointment", body: "Hi, Maison Color cancelled my Saturday slot last minute and I was still charged the deposit. Can you reverse it?",
    category: "Bookings", priority: "Normal", status: "In progress", updated: "1h ago", messages: 3, agent: "Eli R.",
    replyFromAdmin: "Hi Amelia — confirmed the cancellation, refund is in motion. You should see $24 back on Visa ····2118 within 3 business days. Sorry about the disruption.",
    replyTime: "32m ago",
  },
  {
    id: "T-8201", subject: "Loyalty points didn’t apply to last booking", body: "Spent $285 at Maison Color but my Gold tier balance didn’t move. Loyalty page still shows last update Dec 14.",
    category: "Wallet", priority: "Low", status: "Open", updated: "Yesterday", messages: 1, agent: "—",
  },
  {
    id: "T-8104", subject: "Two-factor reset", body: "Got a new phone and lost my authenticator codes. Need to reset 2FA to sign in again.",
    category: "Account", priority: "Urgent", status: "Resolved", updated: "Jan 14", messages: 6, agent: "Mira J.",
    replyFromAdmin: "All sorted — 2FA reset and a new recovery kit emailed. Take care, Amelia.",
    replyTime: "Jan 14",
  },
];

const SAMPLE_VENDOR_TICKETS = [
  {
    id: "T-8201", subject: "Payout not received for Feb 1 batch", body: "We expected $14,820 from PR-9240. ACH says pending but the bank has nothing yet. Can you check the routing?",
    category: "Payouts", priority: "Urgent", status: "In progress", updated: "12m ago", messages: 3, agent: "Mira J.",
    replyFromAdmin: "Hi team — confirmed the file made it to the bank at 22:14 UTC. They have a 1-business-day hold on amounts over $10k. Funds should land tomorrow before noon UTC.",
    replyTime: "8m ago",
  },
  {
    id: "T-8195", subject: "Staff invite email not arriving", body: "Invited two new stylists yesterday, neither got the email. Spam isn’t the issue. Can you trigger a resend or whitelist our domain?",
    category: "Account", priority: "Normal", status: "Open", updated: "2h ago", messages: 1, agent: "—",
  },
  {
    id: "T-8104", subject: "Cancellation policy not applied to no-show", body: "Client no-showed for $285 balayage on Jan 22. Our policy is 50% retained, but Pamp refunded them in full.",
    category: "Bookings", priority: "Normal", status: "Resolved", updated: "Jan 24", messages: 4, agent: "Olu A.",
    replyFromAdmin: "Confirmed — the policy didn’t fire because it was set to 24h notice instead of 48. We’ve adjusted the booking and clawed back the refund. Policy is now 48h.",
    replyTime: "Jan 24",
  },
];

const CLIENT_GUIDES = [
  { ic: <I.calendar />, t: "Rescheduling or cancelling", d: "Most vendors allow free changes up to 24h before. Here’s how." },
  { ic: <I.wallet />, t: "Wallet credit & refunds", d: "How top-ups work, when refunds arrive, and what loyalty points buy." },
  { ic: <I.heart />, t: "Influencer & friend invites", d: "Earn $15 in credit per friend that books their first appointment." },
  { ic: <I.settings />, t: "Two-factor authentication", d: "Secure your account in two minutes with an authenticator app." },
  { ic: <I.bell />, t: "Notification preferences", d: "Pick exactly what you want to hear about — and how." },
  { ic: <I.help />, t: "Disputing a booking", d: "Vendor didn’t deliver? Here’s the right way to flag it." },
];

const VENDOR_GUIDES = [
  { ic: <I.wallet />, t: "Payout schedules & holds", d: "When funds clear, how holds work, and how to switch to instant payouts." },
  { ic: <I.staff />, t: "Adding & managing staff", d: "Invites, role permissions, schedules, and commissions." },
  { ic: <I.coupon />, t: "Smart promos that work", d: "How to fill chairs without giving away the studio." },
  { ic: <I.chart />, t: "Reading your reports", d: "Net revenue, take rate, rebook rate — what to optimize first." },
  { ic: <I.crown />, t: "Upgrading your plan", d: "Studio vs Atelier — when the higher tier actually pays off." },
  { ic: <I.bell />, t: "Notifications to clients", d: "Templates for reminders, follow-ups, and win-back nudges." },
];

window.SupportPage = SupportPage;
