// WhatsApp template picker.
//
// WhatsApp only lets a business message a customer freely for 24 hours after
// their last reply. Past that the composer is replaced by a prompt (see
// WaTemplateGate in composer.jsx) and the only way through is a template Meta
// has already approved. This modal is that step: pick one, preview it, send.
//
// Chrome follows StartNewModal; the table is the shared .ct-table so it matches
// Call Logs and Contacts rather than being a near-miss copy.
const WA_TEMPLATES = [
{
  id: "hello_world",
  name: "hello_world",
  category: "UTILITY",
  language: "English (US)",
  status: "approved",
  header: "Hello World",
  body:
  "Welcome and congratulations!! This message demonstrates your ability to " +
  "send a WhatsApp message notification from the Cloud API, hosted by Meta. " +
  "Thank you for taking the time to test with us.",
  footer: "WhatsApp Business Platform sample message"
},
{
  id: "session_reminder",
  name: "session_reminder",
  category: "UTILITY",
  language: "English (US)",
  status: "approved",
  header: "Session reminder",
  body:
  "Hi {{1}}, this is a reminder about your session with {{2}} on {{3}}. " +
  "Reply here if you need to reschedule and we'll sort it out.",
  footer: "Athlete to Athlete"
},
{
  id: "rebook_nudge",
  name: "rebook_nudge",
  category: "MARKETING",
  language: "English (US)",
  status: "pending",
  header: "Ready for the next one?",
  body:
  "Hi {{1}}, your last session went well — {{2}} has openings this week if " +
  "you'd like to book another.",
  footer: "Reply STOP to opt out"
},
{
  id: "new_marketing_template",
  name: "new_marketing_template",
  category: "MARKETING",
  language: "English (US)",
  status: "rejected",
  header: "Promotional event",
  body:
  "Hello {{1}}, we are reminding you about our promotional event in " +
  "California, USA. Thanks",
  footer: "Reply STOP to opt out"
}];


// Only approved templates can actually be sent — the rest are listed so the
// user can see why the one they were looking for isn't available.
const WA_STATUS_PILL = {
  approved: { cls: "kb-pill ready", label: "Approved" },
  pending: { cls: "kb-pill processing", label: "In review" },
  rejected: { cls: "kb-pill rejected", label: "Rejected" }
};

const WaTemplateModal = ({ open, onClose, onSend, contactName }) => {
  const [q, setQ] = useState("");
  const [picked, setPicked] = useState(null);

  // Reset per open so a previous pick doesn't leak into the next send.
  useEffect(() => {
    if (open) {
      setQ("");
      setPicked(WA_TEMPLATES.find((t) => t.status === "approved") || null);
    }
  }, [open]);

  if (!open) return null;

  const needle = q.trim().toLowerCase();
  const rows = WA_TEMPLATES.filter((t) =>
  !needle ||
  t.name.toLowerCase().includes(needle) ||
  t.category.toLowerCase().includes(needle) ||
  t.body.toLowerCase().includes(needle)
  );

  const canSend = !!picked && picked.status === "approved";

  return (
    <div
      onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}
      style={{
        position: "fixed", inset: 0, zIndex: 200,
        background: "rgba(16,24,40,0.55)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 24,
        animation: "wtmFade .15s ease-out"
      }}>
      <style>{`
        @keyframes wtmFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes wtmIn { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }
        .wtm-tbl { width: 100%; }
        .wtm-row { cursor: pointer; }
        .wtm-row.is-picked > td { background: #EFF8FF !important; }
        .wtm-row.is-blocked { opacity: .55; cursor: not-allowed; }
        .wtm-del { width: 26px; height: 26px; border: none; background: transparent; border-radius: 6px;
                   display: inline-flex; align-items: center; justify-content: center; cursor: pointer; padding: 0; }
        .wtm-del:hover { background: #FEF3F2; }
      `}</style>

      <div
        onMouseDown={(e) => e.stopPropagation()}
        role="dialog" aria-modal="true" aria-label="Send a WhatsApp template"
        style={{
          // Sized so .ct-table gets the ~625px its columns want without having
          // to tighten the shared table's padding for this one screen.
          width: 980, maxWidth: "100%", maxHeight: "100%",
          background: "#FFFFFF", borderRadius: 16,
          boxShadow: "0 24px 48px rgba(16,24,40,0.18), 0 8px 16px rgba(16,24,40,0.10)",
          fontFamily: "Inter, sans-serif",
          display: "flex", flexDirection: "column",
          animation: "wtmIn .18s cubic-bezier(.2,.8,.2,1)"
        }}>

        {/* Header */}
        <div style={{
          display: "flex", alignItems: "flex-start", justifyContent: "space-between",
          gap: 16, padding: "20px 22px 16px", borderBottom: "1px solid #E4E7EC"
        }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600, color: "#101828" }}>
              Send message to {contactName || "this contact"}
            </div>
            <div style={{ fontSize: 13, color: "#667085", marginTop: 2 }}>
              Select a template to start the conversation
            </div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{
            width: 28, height: 28, borderRadius: 6, border: "none", background: "transparent",
            display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
            padding: 0, flexShrink: 0
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = "#F2F4F7"}
          onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
            <I.x size={16} stroke="#475467" />
          </button>
        </div>

        {/* Body — template list on the left, preview on the right */}
        <div style={{ display: "flex", minHeight: 0, flex: 1 }}>

          <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", padding: "16px 22px 18px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <div className="ct-search" style={{ flex: 1 }}>
                <I.search size={15} stroke="#98A2B3" />
                <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search templates" />
              </div>
              <button className="ct-btn-ghost"
              onClick={() => window.dispatchEvent(new CustomEvent("convo:toast", { detail: { msg: "Create template — coming soon" } }))}>
                <I.plus size={14} stroke="#344054" /> Create Template
              </button>
            </div>

            <div className="ct-table-wrap" style={{ flex: 1, minHeight: 0, overflowY: "auto" }}>
              <table className="ct-table wtm-tbl">
                <thead>
                  <tr>
                    <th>Template name</th>
                    <th>Category</th>
                    <th>Language</th>
                    <th>Status</th>
                    <th style={{ width: 44 }} aria-label="Actions" />
                  </tr>
                </thead>
                <tbody>
                  {rows.map((t) => {
                    const pill = WA_STATUS_PILL[t.status];
                    const blocked = t.status !== "approved";
                    return (
                      <tr key={t.id}
                      className={`wtm-row${picked && picked.id === t.id ? " is-picked" : ""}${blocked ? " is-blocked" : ""}`}
                      onClick={() => setPicked(t)}
                      title={blocked ? "Only approved templates can be sent" : undefined}>
                        <td><span className="cv-name-link">{t.name}</span></td>
                        <td><span className="vc-tpl-tag">{t.category}</span></td>
                        <td>{t.language}</td>
                        <td><span className={pill.cls}>{pill.label}</span></td>
                        <td>
                          <button className="wtm-del" aria-label={`Delete ${t.name}`}
                          onClick={(e) => {
                            e.stopPropagation();
                            window.dispatchEvent(new CustomEvent("convo:toast", { detail: { msg: "Delete template — coming soon" } }));
                          }}>
                            <I.trash size={14} stroke="#D92D20" />
                          </button>
                        </td>
                      </tr>);

                  })}
                  {rows.length === 0 &&
                  <tr>
                      <td colSpan={5} style={{ textAlign: "center", color: "#98A2B3", padding: "28px 0" }}>
                        No templates match “{q}”
                      </td>
                    </tr>
                  }
                </tbody>
              </table>
            </div>
          </div>

          {/* Preview — the bubble as WhatsApp will render it */}
          <div style={{
            width: 300, flexShrink: 0, borderLeft: "1px solid #E4E7EC",
            background: "#F9FAFB", padding: "16px 18px 18px",
            display: "flex", flexDirection: "column", minHeight: 0
          }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "#344054", marginBottom: 10 }}>
              Message preview
            </div>
            {picked ?
            <div style={{ overflowY: "auto", minHeight: 0 }}>
                <div style={{
                background: "#DCF8C6", borderRadius: 10, padding: "10px 12px",
                boxShadow: "0 1px 2px rgba(16,24,40,.06)"
              }}>
                  {picked.header &&
                <div style={{ fontSize: 13, fontWeight: 600, color: "#101828", marginBottom: 4 }}>
                      {picked.header}
                    </div>
                }
                  <div style={{ fontSize: 13, color: "#101828", lineHeight: 1.5, whiteSpace: "pre-wrap" }}>
                    {picked.body}
                  </div>
                  {picked.footer &&
                <div style={{ fontSize: 11, color: "#667085", marginTop: 8 }}>{picked.footer}</div>
                }
                </div>
                {/* Variables are filled in from the contact record at send time. */}
                {/\{\{\d+\}\}/.test(picked.body) &&
              <div style={{ fontSize: 11, color: "#667085", marginTop: 10, lineHeight: 1.5 }}>
                    Values in <span style={{ fontFamily: "'IBM Plex Mono', ui-monospace, monospace" }}>{"{{ }}"}</span> are
                    filled from the contact record when the message is sent.
                  </div>
              }
              </div> :

            <div style={{ fontSize: 12, color: "#98A2B3" }}>Select a template to preview it.</div>
            }
          </div>
        </div>

        {/* Footer */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 10,
          padding: "14px 22px", borderTop: "1px solid #E4E7EC"
        }}>
          <button className="ct-btn-ghost" onClick={onClose}>Cancel</button>
          <button
            onClick={() => canSend && onSend(picked)}
            disabled={!canSend}
            style={{
              height: 36, padding: "0 18px", borderRadius: 8, border: "none",
              background: canSend ? "#004CE6" : "#EAECF0",
              color: canSend ? "#FFFFFF" : "#98A2B3",
              fontSize: 13, fontWeight: 600, fontFamily: "inherit",
              cursor: canSend ? "pointer" : "not-allowed"
            }}>Send</button>
        </div>
      </div>
    </div>);

};

window.WaTemplateModal = WaTemplateModal;
