/* ========================================================================
   support.jsx — Support Tickets (brought in line with production)
   List, create, edit and detail, plus the Need More Help panel. Platform
   raised requests and CSV batches appear in the same list, since they are
   also things sent to the team.
   ======================================================================== */
const { useState: uS, useEffect: eS, useMemo: mS, useRef: rS } = React;
const SD = window.MILO_DATA;

const CATEGORIES = ["Technical Issue", "SIM Issue", "SIM Management", "Billing & Invoicing", "Environmental Reporting", "Order or Request Handset", "Other"];
const PRIORITIES = ["Low", "Medium", "High", "Critical"];
const PRIORITY_HELP = "Low: general questions · Medium: affecting some users · High: service disruption · Critical: complete outage";
const FILE_HELP = "Supported formats: JPEG, PNG, PDF, TXT · Max 10 MB per file";

/* ---------- Store ---------- */
const TK_KEY = "mp_support_tickets_v1";
let TK = { seq: 0, list: [] };
try { const raw = localStorage.getItem(TK_KEY); if (raw) TK = { ...TK, ...JSON.parse(raw) }; } catch (e) {}
const tkSubs = new Set();
function tkNotify() {
  try { localStorage.setItem(TK_KEY, JSON.stringify(TK)); } catch (e) {}
  tkSubs.forEach((cb) => cb());
}
function useTickets() {
  const [, force] = uS(0);
  eS(() => { const cb = () => force((n) => n + 1); tkSubs.add(cb); return () => tkSubs.delete(cb); }, []);
  return TK;
}
const ticketById = (id) => TK.list.find((t) => String(t.id) === String(id)) || null;

function createTicket(fields) {
  TK.seq += 1;
  const t = {
    id: TK.seq, ...fields,
    status: "Created",
    created: new Date().toISOString(),
    comments: []
  };
  TK.list.unshift(t);
  tkNotify();
  return t;
}
function updateTicket(id, fields) {
  const t = ticketById(id);
  if (t) { Object.assign(t, fields); tkNotify(); }
  return t;
}
function addComment(id, body, files) {
  const t = ticketById(id);
  if (!t) return null;
  t.comments.push({ id: t.comments.length + 1, author: SD.CURRENT_USER.full_name, body, files: files || [], at: new Date().toISOString() });
  tkNotify();
  return t;
}

const fmtCreated = (iso) => new Date(iso).toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" });
const fmtCreatedFull = (iso) => fmtCreated(iso) + ", " + new Date(iso).toTimeString().slice(0, 5);

/* ---------- Need More Help ---------- */
function NeedMoreHelpCard() {
  const rows = [
    { icon: "message-square", label: "Live Chat Support", sub: "Available Mon–Fri, 9:00–17:00", chev: "chevron-right",
      demo: "Live Chat opens the support chat in the live platform." },
    { icon: "phone", label: "Phone Support: 020 4552 9816", chev: "chevron-right",
      demo: "Phone Support dials the team in the live platform." },
    { icon: "book-open", label: "Help Centre", chev: "external-link",
      demo: "The Help Centre opens in a new tab in the live platform." }];
  return (
    <Card>
      <div className="mp-card-body">
        <h3 className="mp-help-title">Need More Help?</h3>
        <p className="mp-help-sub">Can't find what you're looking for? We're here to help.</p>
        <div className="mp-help-rows">
          {rows.map((r) =>
            <button type="button" className="mp-help-row" key={r.label}
              onClick={(e) => { if (window.DEMO_TOAST) window.DEMO_TOAST(r.demo, e); }}>
              <Icon name={r.icon} size={17} />
              <span className="mp-help-row-body">
                <span className="mp-help-row-label">{r.label}</span>
                {r.sub ? <span className="mp-help-row-sub">{r.sub}</span> : null}
              </span>
              <Icon name={r.chev} size={15} />
            </button>)}
        </div>
      </div>
    </Card>);
}

/* ---------- Attachments ---------- */
function FileDrop({ files, onAdd, onRemove }) {
  const input = rS(null);
  const [over, setOver] = uS(false);
  const take = (list) => {
    const names = Array.from(list || []).map((f) => ({ name: f.name, size: f.size }));
    if (names.length) onAdd(names);
  };
  return (
    <>
      <div className="mp-attach-label">Attachments</div>
      {files.length === 0 ?
        <p className="mp-attach-none">No attachments</p> :
        <ul className="mp-attach-list">
          {files.map((f, i) =>
            <li key={f.name + i}>
              <Icon name="paperclip" size={14} />
              <span>{f.name}</span>
              <button type="button" aria-label={"Remove " + f.name} onClick={() => onRemove(i)}><Icon name="x" size={13} /></button>
            </li>)}
        </ul>}
      <div className={"mp-filedrop" + (over ? " is-over" : "")}
        onDragOver={(e) => { e.preventDefault(); setOver(true); }}
        onDragLeave={() => setOver(false)}
        onDrop={(e) => { e.preventDefault(); setOver(false); take(e.dataTransfer.files); }}>
        <input ref={input} type="file" multiple hidden accept=".jpg,.jpeg,.png,.pdf,.txt"
          onChange={(e) => { take(e.target.files); e.target.value = ""; }} />
        <p className="mp-filedrop-title">Drag and drop files here, or</p>
        <Button variant="secondary" size="sm" onClick={() => input.current && input.current.click()}>Choose Files</Button>
        <p className="mp-filedrop-msg">{FILE_HELP}</p>
      </div>
    </>);
}

/* ---------- List ---------- */
/* Requests and batches are also things sent to the team, so they are listed
   here beside tickets the user wrote. */
function platformRows() {
  const out = [];
  const R = window.MP_REQ, B = window.MP_BATCH;
  if (R && R.allRequests) {
    const seen = {};
    R.allRequests().forEach((r) => {
      if (r.batch) { if (seen[r.batch]) return; seen[r.batch] = true; }
      const sim = r.simId ? SD.SIMS.find((s) => s.id === r.simId) : null;
      const count = r.batch ? R.allRequests().filter((x) => x.batch === r.batch).length : 1;
      out.push({
        key: "r" + r.id, ref: "#" + r.ticket, subject: R.requestSubject(r),
        description: R.requestDetail ? R.requestDetail(r, count, sim) : (count > 1 ? count + " SIMs" : sim ? sim.msisdn : ""),
        category: "SIM Management", priority: "Low",
        status: r.status === "open" ? "In Progress" : r.status === "completed" ? "Resolved" : "Declined",
        created: r.created, href: sim ? "#/sims/" + sim.id : null, hrefLabel: "View SIM"
      });
    });
  }
  if (B && B.all) B.all().forEach((b) => out.push({
    key: b.id, ref: b.ref,
    subject: b.kind === "import" ? "User import" : "SIM assignment",
    description: b.rows.length + (b.kind === "import" ? " record" : " SIM") + (b.rows.length === 1 ? "" : "s"),
    category: "SIM Management", priority: "Low",
    status: b.status === "submitted" ? "In Progress" : "Resolved",
    created: b.submitted_at, batch: b.status === "complete" ? b : null
  }));
  return out;
}

function StatusPill({ status }) {
  const k = (status || "").toLowerCase().replace(/\s+/g, "-");
  return <span className={"mp-tk-status mp-tk-status--" + k}>{status}</span>;
}
function PriorityPill({ priority }) {
  if (!priority) return <span className="mp-tk-nopriority">Not set</span>;
  return <span className={"mp-tk-priority mp-tk-priority--" + priority.toLowerCase()}>{priority}</span>;
}

function SupportTicketsPage() {
  useTickets();
  if (window.MP_REQ) window.MP_REQ.useRequests();
  if (window.MP_BATCH) window.MP_BATCH.useBatches();
  const [query, setQuery] = uS("");
  const [status, setStatus] = uS("");
  const [results, setResults] = uS(null);
  eS(() => { if (window.lucide) { try { window.lucide.createIcons(); } catch (e) {} } });

  const rows = mS(() => {
    const mine = TK.list.map((t) => ({
      key: "t" + t.id, ref: String(t.id), subject: t.subject, description: t.description,
      category: t.category, priority: t.priority, status: t.status, created: t.created,
      href: "#/support/tickets/" + t.id, hrefLabel: "View Ticket"
    }));
    return mine.concat(platformRows()).sort((a, b) => new Date(b.created) - new Date(a.created));
  }, [TK.list.length, TK.seq]);

  const statuses = mS(() => {
    const seen = [];
    rows.forEach((r) => { if (seen.indexOf(r.status) === -1) seen.push(r.status); });
    return seen;
  }, [rows]);

  const filtered = rows.filter((r) => {
    if (status && r.status !== status) return false;
    if (!query.trim()) return true;
    const q = query.trim().toLowerCase();
    return [r.ref, r.subject, r.description, r.category].some((v) => String(v || "").toLowerCase().includes(q));
  });
  const dirty = query || status;

  return (
    <>
      <PageHead title="Support Tickets" />
      <BackLink href="#/support">Back to Support &amp; Help</BackLink>

      <div className="mp-tk-bar">
        <SearchInput value={query} onChange={setQuery} placeholder="Search tickets…" />
        <Select value={status} onChange={setStatus} placeholder="All"
          options={statuses.map((s) => ({ value: s, label: s }))} />
        {dirty ?
        <div className="mp-clear">
          <Button variant="secondary" size="sm" icon="x" onClick={() => { setQuery(""); setStatus(""); }}>Clear Filters</Button>
        </div> : null}
      </div>

      <div className="mp-page-actions">
        <Button variant="primary" href="#/support/tickets/new">Create Support Ticket</Button>
      </div>

      <div>
        <div>
          {filtered.length === 0 ?
          <Card>
            <div className="mp-card-body">
              <Empty icon="ticket"
                title={rows.length ? "No tickets match" : "No support tickets yet"}
                message={rows.length ? "Try a different search or clear the filters." : "When you create a support ticket, it will appear here."} />
              {rows.length === 0 ?
              <div className="mp-tk-empty-cta">
                <Button variant="primary" href="#/support/tickets/new">Create Support Ticket</Button>
              </div> : null}
            </div>
          </Card> :
          <Card style={{ overflow: "hidden" }}>
            <TableScroll>
              <table className="mp-table">
                <thead>
                  <tr>
                    <th>ID</th><th>Subject</th><th>Description</th><th>Category</th>
                    <th>Priority</th><th>Status</th><th>Created</th><th></th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((r) =>
                    <tr key={r.key}>
                      <td className="mp-mono">{r.ref}</td>
                      <td className="mp-tk-subject">{r.subject}</td>
                      <td className="mp-tk-desc">{r.description}</td>
                      <td>{r.category}</td>
                      <td><PriorityPill priority={r.priority} /></td>
                      <td><StatusPill status={r.status} /></td>
                      <td className="mp-nowrap">{fmtCreated(r.created)}</td>
                      <td><ActionsMenu items={
                        r.batch ? [{ label: "View Results", onClick: () => setResults(r.batch) }] :
                        r.href ? [{ label: r.hrefLabel, href: r.href }] :
                        [{ note: "Nothing to open yet, the team will be in touch." }]} /></td>
                    </tr>)}
                </tbody>
              </table>
            </TableScroll>
          </Card>}
        </div>
      </div>

      {results && window.BatchResultsModal ?
        <window.BatchResultsModal batch={results} onClose={() => setResults(null)} /> : null}
    </>);
}

/* ---------- Create and edit ---------- */
function SupportTicketFormPage({ id }) {
  const ctx = window.useRoles ? window.useRoles() : null;
  useTickets();
  const existing = id ? ticketById(id) : null;
  const [subject, setSubject] = uS(existing ? existing.subject : "");
  const [category, setCategory] = uS(existing ? existing.category : CATEGORIES[0]);
  const [priority, setPriority] = uS(existing ? existing.priority : PRIORITIES[0]);
  const [description, setDescription] = uS(existing ? existing.description : "");
  const [files, setFiles] = uS(existing ? (existing.attachments || []).slice() : []);
  eS(() => { if (window.lucide) { try { window.lucide.createIcons(); } catch (e) {} } });

  const ready = subject.trim() && description.trim();
  const submit = () => {
    const fields = { subject: subject.trim(), category, priority, description: description.trim(), attachments: files };
    if (existing) {
      updateTicket(existing.id, fields);
      if (ctx) ctx.toast({ kind: "ok", title: "Ticket updated" });
      location.hash = "/support/tickets/" + existing.id;
      return;
    }
    const t = createTicket(fields);
    if (ctx) ctx.toast({ kind: "ok", title: "Ticket created", body: "We will get back to you as soon as possible." });
    location.hash = "/support/tickets/" + t.id;
  };

  return (
    <>
      <PageHead title={existing ? "Edit Support Ticket" : "Create Support Ticket"}
        subtitle={existing ? "Update the details of your support request." : "Describe your issue and we'll get back to you as soon as possible."} />
      <BackLink href="#/support/tickets">Back to Support Tickets</BackLink>

      <div>
        <Card>
          <div className="mp-card-body">
            <div className="mp-field">
              <label className="mp-field-label">Subject</label>
              <input className="mp-field-input" value={subject} onChange={(e) => setSubject(e.target.value)}
                placeholder={"Brief summary of the issue (e.g., \u201cSIM not connecting to network\u201d)"} />
            </div>
            <div className="mp-field">
              <label className="mp-field-label">Category</label>
              <Select value={category} onChange={setCategory} options={CATEGORIES.map((c) => ({ value: c, label: c }))} />
              <div className="mp-field-help">Choose the category that best describes your issue. This helps us route your ticket to the right team.</div>
            </div>
            <div className="mp-field">
              <label className="mp-field-label">Priority <span className="mp-req-star">*</span></label>
              <Select value={priority} onChange={setPriority} options={PRIORITIES.map((p) => ({ value: p, label: p }))} />
              <div className="mp-field-help">{PRIORITY_HELP}</div>
            </div>
            <div className="mp-field">
              <label className="mp-field-label">Description <span className="mp-req-star">*</span></label>
              <textarea className="mp-field-input" rows={6} value={description} onChange={(e) => setDescription(e.target.value)}
                placeholder="Include what happened, when it started, and which SIMs or users are affected" />
              <div className="mp-field-help">The more detail you provide, the faster we can help. Include SIM serial numbers, phone numbers, or error messages if relevant.</div>
            </div>

            <FileDrop files={files}
              onAdd={(add) => setFiles(files.concat(add))}
              onRemove={(i) => setFiles(files.filter((f, n) => n !== i))} />

            <div className="mp-tk-foot">
              <Button variant="primary" className={ready ? "" : "is-disabled"}
                onClick={ready ? submit : undefined}>{existing ? "Save Changes" : "Submit Support Ticket"}</Button>
            </div>
          </div>
        </Card>
      </div>
    </>);
}

/* ---------- Detail ---------- */
function SupportTicketShowPage({ id }) {
  const ctx = window.useRoles ? window.useRoles() : null;
  useTickets();
  const t = ticketById(id);
  const [reply, setReply] = uS("");
  const [files, setFiles] = uS([]);
  eS(() => { if (window.lucide) { try { window.lucide.createIcons(); } catch (e) {} } });

  if (!t) return (
    <>
      <PageHead title="Support Ticket" />
      <BackLink href="#/support/tickets">Back to Support Tickets</BackLink>
      <Card><div className="mp-card-body">
        <Empty icon="ticket" title="Ticket not found" message="This ticket may have been removed." />
      </div></Card>
    </>);

  const send = () => {
    addComment(t.id, reply.trim(), files);
    setReply(""); setFiles([]);
    if (ctx) ctx.toast({ kind: "ok", title: "Reply sent" });
  };

  return (
    <>
      <PageHead title={"Support Ticket #" + t.id} />
      <div className="mp-tk-head-row">
        <BackLink href="#/support/tickets">Back to Support Tickets</BackLink>
        <Button variant="secondary" size="sm" href={"#/support/tickets/" + t.id + "/edit"}>Edit Support Ticket</Button>
      </div>

      <div className="mp-support-grid">
        <Card style={{ overflow: "hidden" }}>
          <div className="mp-tk-hero">
            <div>
              <h3 className="mp-tk-hero-title">Ticket #{t.id}</h3>
              <div className="mp-tk-hero-sub">Created: {fmtCreatedFull(t.created)}</div>
            </div>
            <StatusPill status={t.status} />
          </div>
          <div className="mp-card-body">
            <div className="mp-tk-grid">
              <div>
                <h4 className="mp-tk-h">Requester Information</h4>
                <p className="mp-tk-p">Name: {SD.CURRENT_USER.full_name}</p>
                <p className="mp-tk-p">Email: {SD.CURRENT_USER.email}</p>
              </div>
              <div>
                <h4 className="mp-tk-h">Ticket Details</h4>
                <p className="mp-tk-p">Priority: <PriorityPill priority={t.priority} /></p>
                <p className="mp-tk-p">Category: {t.category}</p>
              </div>
            </div>

            <h4 className="mp-tk-h">Subject</h4>
            <div className="mp-tk-readout">{t.subject}</div>

            <h4 className="mp-tk-h">Issue Description</h4>
            <div className="mp-tk-readout">{t.description}</div>

            <h4 className="mp-tk-h">Attachments</h4>
            {(t.attachments || []).length === 0 ?
              <p className="mp-attach-none">No attachments</p> :
              <ul className="mp-attach-list mp-attach-list--static">
                {t.attachments.map((f, i) => <li key={f.name + i}><Icon name="paperclip" size={14} /><span>{f.name}</span></li>)}
              </ul>}

            <h4 className="mp-tk-h">Comments</h4>
            {t.comments.length === 0 ?
              <p className="mp-attach-none">No comments yet. Replies from our support team will appear here.</p> :
              <div className="mp-tk-comments">
                {t.comments.map((c) =>
                  <div className="mp-tk-comment" key={c.id}>
                    <div className="mp-tk-comment-head">
                      <Avatar initials={SD.CURRENT_USER.initials} size={26} tone="mist" />
                      <strong>{c.author}</strong>
                      <span>{fmtCreatedFull(c.at)}</span>
                    </div>
                    <p className="mp-tk-comment-body">{c.body}</p>
                    {c.files && c.files.length ?
                      <ul className="mp-attach-list mp-attach-list--static">
                        {c.files.map((f, i) => <li key={f.name + i}><Icon name="paperclip" size={14} /><span>{f.name}</span></li>)}
                      </ul> : null}
                  </div>)}
              </div>}

            <div className="mp-tk-reply">
              <h4 className="mp-tk-h">Add a Reply</h4>
              <div className="mp-field">
                <label className="mp-field-label">Your message</label>
                <textarea className="mp-field-input" rows={4} value={reply} onChange={(e) => setReply(e.target.value)}
                  placeholder="Type your reply here…" />
              </div>
              <FileDrop files={files}
                onAdd={(add) => setFiles(files.concat(add))}
                onRemove={(i) => setFiles(files.filter((f, n) => n !== i))} />
              <div className="mp-tk-foot">
                <Button variant="primary" className={reply.trim() ? "" : "is-disabled"}
                  onClick={reply.trim() ? send : undefined}>Send Reply</Button>
              </div>
            </div>
          </div>
        </Card>
        <NeedMoreHelpCard />
      </div>
    </>);
}

Object.assign(window, {
  SupportTicketsPage, SupportTicketFormPage, SupportTicketShowPage, NeedMoreHelpCard,
  MP_TICKETS: { useTickets, createTicket, ticketById, count: () => TK.list.length }
});
