import React, { useEffect, useMemo, useState } from "react";
import { bpFetch } from "../api/client";
import WorkflowEditScreen from "./WorkflowEditScreen";
import { Modal } from "../ui/Modal";
import ProContextCard from "../components/ProContextCard";

const EVENT_LABELS = {
  booking_created: "Booking Created",
  booking_updated: "Booking Updated",
  booking_confirmed: "Booking Confirmed",
  booking_cancelled: "Booking Cancelled",
  booking_abandoned: "Booking Abandoned",
  customer_created: "Customer Created",
};

const PRO_CAPABILITY_GROUPS = [
  {
    title: "Automation",
    lead: "Advanced workflows and outbound automation channels.",
    items: [
      {
        key: "advanced_workflows",
        label: "Advanced workflows",
        description: "Multi-step workflows with conditions and delays.",
        actionTypes: [],
      },
      {
        key: "advanced_webhooks",
        label: "Advanced webhooks",
        description: "Signed webhook delivery to external automation endpoints.",
        actionTypes: ["send_webhook"],
      },
      {
        key: "sms_reminders",
        label: "SMS reminders",
        description: "Send SMS notifications through Twilio.",
        actionTypes: ["send_sms"],
      },
      {
        key: "whatsapp_notifications",
        label: "WhatsApp notifications",
        description: "Send WhatsApp notifications through Twilio.",
        actionTypes: ["send_whatsapp"],
      },
      {
        key: "mailchimp_crm",
        label: "Mailchimp and CRM integrations",
        description: "Sync contacts with Mailchimp, HubSpot, and CRM webhooks.",
        actionTypes: ["mailchimp_subscribe", "hubspot_upsert_contact", "crm_webhook"],
      },
    ],
  },
  {
    title: "Integrations",
    lead: "Calendar sync, meeting links, and payment ecosystem connections.",
    items: [
      {
        key: "google_calendar_sync",
        label: "Google Calendar sync",
        description: "Create, update, and remove Google Calendar events.",
        actionTypes: ["google_calendar_sync"],
      },
      {
        key: "outlook_calendar_sync",
        label: "Outlook and Microsoft 365 sync",
        description: "Sync bookings with Outlook / Microsoft 365 calendars.",
        actionTypes: ["outlook_calendar_sync"],
      },
      {
        key: "video_meetings",
        label: "Zoom and Google Meet links",
        description: "Generate Zoom and Google Meet meeting links per booking.",
        actionTypes: ["zoom_meeting_create", "google_meet_link"],
      },
      {
        key: "extra_payment_gateways",
        label: "More payment gateways",
        description: "Use WooCommerce as the gateway hub for additional processors.",
        actionTypes: [],
      },
    ],
  },
  {
    title: "Revenue Tools",
    lead: "Recurring, package, invoice, payment-link, and refund workflows.",
    items: [
      {
        key: "recurring_appointments",
        label: "Recurring appointments",
        description: "Generate recurring bookings from a source booking.",
        actionTypes: ["create_recurring_appointments"],
      },
      {
        key: "packages_bundles",
        label: "Packages and bundles",
        description: "Sell packages and redeem package credits from workflows.",
        actionTypes: ["create_package_purchase", "redeem_package_credit"],
      },
      {
        key: "deposits_partial_payments",
        label: "Deposits and partial payments",
        description: "Create deposit links and collect partial amounts.",
        actionTypes: ["create_deposit_payment_link"],
      },
      {
        key: "invoices",
        label: "Invoices",
        description: "Generate invoice records and hosted invoice pages.",
        actionTypes: ["create_invoice"],
      },
      {
        key: "payment_links",
        label: "Payment links",
        description: "Create secure hosted payment links for bookings.",
        actionTypes: ["create_payment_link"],
      },
      {
        key: "refund_management",
        label: "Refund management",
        description: "Record and process refunds using provider references.",
        actionTypes: ["refund_payment"],
      },
    ],
  },
  {
    title: "Business Controls",
    lead: "Reporting, role controls, and timezone-aware scheduling.",
    items: [
      {
        key: "advanced_reports",
        label: "Advanced reports",
        description: "System reports, diagnostics, and export tooling.",
        actionTypes: [],
      },
      {
        key: "agent_dashboard",
        label: "Agent dashboard",
        description: "Agent-focused booking, calendar, and schedule views.",
        actionTypes: [],
      },
      {
        key: "advanced_roles_permissions",
        label: "Advanced roles and permissions",
        description: "Granular capability control for manager and staff roles.",
        actionTypes: [],
      },
      {
        key: "timezone_picker",
        label: "Timezone picker",
        description: "Select and persist booking schedule timezone behavior.",
        actionTypes: [],
      },
    ],
  },
  {
    title: "Button and Widget Customization",
    lead: "Control booking button behavior, preselects, skips, and widget style.",
    items: [
      {
        key: "button_widget_customization",
        label: "Custom booking button text / color / size / radius / icon / full-width",
        description: "Style and behavior options passed through shortcode attributes.",
        actionTypes: [],
      },
      {
        key: "button_widget_customization",
        label: "Service-specific booking buttons",
        description: "Preset service and launch focused service-entry buttons.",
        actionTypes: [],
      },
      {
        key: "shortcode_step_skipping",
        label: "Shortcode preselect and step skipping",
        description: "Preselect location/category/service/agent and skip selected steps.",
        actionTypes: [],
      },
      {
        key: "button_widget_customization",
        label: "Advanced widget styling",
        description: "Override modal primary, overlay, background, radius, and width.",
        actionTypes: [],
      },
    ],
  },
];

export default function NotificationsScreen() {
  const admin = window.pointlybooking_ADMIN || {};
  const features = admin.features || {};
  const proActive = Boolean(admin.proActive);

  const [workflows, setWorkflows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [toast, setToast] = useState("");

  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [eventFilter, setEventFilter] = useState("");

  const [selectedId, setSelectedId] = useState(null);
  const [showEditor, setShowEditor] = useState(false);
  const [tick, setTick] = useState(0);
  const [meta, setMeta] = useState({ events: Object.keys(EVENT_LABELS), counts: {}, action_types: {} });

  const [templatesOpen, setTemplatesOpen] = useState(false);
  const [busyId, setBusyId] = useState(null);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(""), 2500);
  };

  useEffect(() => {
    loadWorkflows();
    loadMeta();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search, statusFilter, eventFilter, tick]);

  async function loadWorkflows() {
    setLoading(true);
    setError("");
    try {
      const query = new URLSearchParams();
      if (search) query.set("q", search);
      if (statusFilter && statusFilter !== "all") query.set("status", statusFilter);
      if (eventFilter) query.set("event", eventFilter);
      query.set("page", "1");
      query.set("per", "50");
      const resp = await bpFetch(`/admin/notifications/workflows?${query.toString()}`);
      setWorkflows(resp?.data?.items || []);
    } catch (err) {
      setWorkflows([]);
      setError(err.message || "Failed to load workflows.");
    } finally {
      setLoading(false);
    }
  }

  async function loadMeta() {
    try {
      const resp = await bpFetch("/admin/notifications/meta");
      if (resp?.data) setMeta(resp.data);
    } catch (_) {
      // optional
    }
  }

  function openEditor(id) {
    setSelectedId(id);
    setShowEditor(true);
    window.location.hash = `#/notifications/${id}`;
  }

  function closeEditor() {
    setShowEditor(false);
    setSelectedId(null);
    window.history.replaceState(null, "", window.location.pathname);
  }

  async function addWorkflow() {
    setError("");
    try {
      const resp = await bpFetch("/admin/notifications/workflows", {
        method: "POST",
        body: {
          name: "New workflow",
          event_key: "booking_created",
          status: "active",
        },
      });
      if (resp?.data?.id) {
        setTick((prev) => prev + 1);
        openEditor(resp.data.id);
      }
    } catch (err) {
      setError(err.message || "Could not create workflow.");
    }
  }

  async function toggleWorkflowStatus(workflow) {
    const next = workflow.status === "active" ? "disabled" : "active";
    setBusyId(workflow.id);
    setError("");
    try {
      await bpFetch(`/admin/notifications/workflows/${workflow.id}`, { method: "PUT", body: { status: next } });
      setWorkflows((prev) => prev.map((w) => (w.id === workflow.id ? { ...w, status: next } : w)));
      showToast(next === "active" ? "Enabled." : "Disabled.");
      loadMeta();
    } catch (err) {
      setError(err.message || "Could not update workflow.");
    } finally {
      setBusyId(null);
    }
  }

  async function testWorkflow(workflowId) {
    if (!confirm("Run workflow test now? This will trigger all ACTIVE actions using the latest booking.")) return;
    setBusyId(workflowId);
    setError("");
    try {
      const resp = await bpFetch(`/admin/notifications/workflows/${workflowId}/test`, { method: "POST" });
      const results = resp?.data?.results || [];
      const sent = results.filter((r) => r.sent).length;
      showToast(`Test complete: ${sent}/${results.length} action(s) sent.`);
      setTick((prev) => prev + 1);
    } catch (err) {
      setError(err.message || "Test failed.");
    } finally {
      setBusyId(null);
    }
  }

  async function deleteWorkflow(workflow) {
    if (!workflow?.id) return;
    if (!confirm(`Delete workflow \"${workflow.name || workflow.id}\"? This cannot be undone.`)) return;
    setBusyId(workflow.id);
    setError("");
    try {
      await bpFetch(`/admin/notifications/workflows/${workflow.id}`, { method: "DELETE" });
      setWorkflows((prev) => prev.filter((w) => w.id !== workflow.id));
      showToast("Workflow deleted.");
      loadMeta();
    } catch (err) {
      setError(err.message || "Delete failed.");
    } finally {
      setBusyId(null);
    }
  }

  const actionTypes = useMemo(() => {
    if (!meta || typeof meta !== "object") return {};
    return meta.action_types && typeof meta.action_types === "object" ? meta.action_types : {};
  }, [meta]);

  const capabilityGroups = useMemo(
    () =>
      PRO_CAPABILITY_GROUPS.map((group) => {
        const items = group.items.map((item) => {
          const featureEnabled = Boolean(features[item.key]);
          const actionsReady =
            !item.actionTypes.length || item.actionTypes.some((type) => Boolean(actionTypes[type]));
          return {
            ...item,
            ready: featureEnabled && actionsReady,
          };
        });

        const readyCount = items.filter((item) => item.ready).length;
        return {
          ...group,
          items,
          readyCount,
          totalCount: items.length,
        };
      }),
    [features, actionTypes]
  );

  const baseTemplates = useMemo(
    () => [
      {
        id: "booking_created_customer",
        name: "Booking Created -> Email Customer",
        event_key: "booking_created",
        workflow_name: "Booking Created: Customer email",
        actions: [
          {
            type: "send_email",
            status: "active",
            config: {
              to: "{{customer_email}}",
              from_name: "{{site_name}}",
              from_email: "{{admin_email}}",
              subject: "Booking received (#{{booking_id}})",
              body:
                "<p>Hi {{customer_name}},</p>" +
                "<p>We received your booking for <strong>{{service_name}}</strong> on {{start_date}} at {{start_time}}.</p>" +
                "<p>You can manage your booking here: <a href=\"{{manage_booking_url_customer}}\">Manage booking</a>.</p>" +
                "<p>Thanks,<br>{{site_name}}</p>",
              attach_ics: true,
            },
          },
        ],
      },
      {
        id: "booking_confirmed_customer",
        name: "Booking Confirmed -> Email Customer",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: Customer email",
        actions: [
          {
            type: "send_email",
            status: "active",
            config: {
              to: "{{customer_email}}",
              from_name: "{{site_name}}",
              from_email: "{{admin_email}}",
              subject: "Booking confirmed (#{{booking_id}})",
              body:
                "<p>Hi {{customer_name}},</p>" +
                "<p>Your booking for <strong>{{service_name}}</strong> is confirmed for {{start_date}} at {{start_time}}.</p>" +
                "<p>Manage your booking: <a href=\"{{manage_booking_url_customer}}\">Manage booking</a>.</p>" +
                "<p>Thanks,<br>{{site_name}}</p>",
              attach_ics: true,
            },
          },
        ],
      },
      {
        id: "booking_cancelled_admin",
        name: "Booking Cancelled -> Email Admin",
        event_key: "booking_cancelled",
        workflow_name: "Booking Cancelled: Admin notification",
        actions: [
          {
            type: "send_email",
            status: "active",
            config: {
              to: "{{admin_email}}",
              from_name: "{{site_name}}",
              from_email: "{{admin_email}}",
              subject: "Booking cancelled (#{{booking_id}})",
              body:
                "<p>A booking was cancelled.</p>" +
                "<ul>" +
                "<li>ID: {{booking_id}}</li>" +
                "<li>Customer: {{customer_name}} ({{customer_email}})</li>" +
                "<li>Service: {{service_name}}</li>" +
                "<li>When: {{start_date}} {{start_time}}</li>" +
                "</ul>",
              attach_ics: false,
            },
          },
        ],
      },
      {
        id: "booking_abandoned_customer",
        name: "Booking Abandoned -> Recovery Email",
        event_key: "booking_abandoned",
        workflow_name: "Booking Abandoned: Recovery email",
        actions: [
          {
            type: "send_email",
            status: "active",
            config: {
              to: "{{customer_email}}",
              from_name: "{{site_name}}",
              from_email: "{{admin_email}}",
              subject: "Finish your booking for {{service_name}}",
              body:
                "<p>Hi {{customer_name}},</p>" +
                "<p>You started booking <strong>{{service_name}}</strong> but did not finish.</p>" +
                "<p>Resume here: <a href=\"{{resume_url}}\">Complete your booking</a>.</p>" +
                "<p>If you need help, reply to this email and our team will help you finish the booking.</p>" +
                "<p>Thanks,<br>{{site_name}}</p>",
              attach_ics: false,
            },
          },
        ],
      },
    ],
    []
  );

  const automationTemplates = useMemo(() => {
    const templates = [];

    if (actionTypes.send_webhook) {
      templates.push({
        id: "pro_advanced_webhook",
        name: "Booking Created -> Advanced Webhook",
        event_key: "booking_created",
        workflow_name: "Booking Created: Advanced webhook",
        actions: [
          {
            type: "send_webhook",
            status: "active",
            config: {
              url: "",
              method: "POST",
              secret: "",
              headers: "",
              payload_template:
                '{"event":"{{event_key}}","booking_id":"{{booking_id}}","customer_email":"{{customer_email}}","customer_phone":"{{customer_phone}}","service_name":"{{service_name}}","start_datetime":"{{start_datetime}}"}',
            },
          },
        ],
      });
    }

    if (actionTypes.send_sms) {
      templates.push({
        id: "pro_sms_reminder",
        name: "Booking Confirmed -> SMS Reminder",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: SMS reminder",
        actions: [
          {
            type: "send_sms",
            status: "active",
            config: {
              account_sid: "",
              auth_token: "",
              from: "",
              messaging_service_sid: "",
              to: "{{customer_phone}}",
              body: "Reminder: {{service_name}} on {{start_date}} at {{start_time}}.",
            },
          },
        ],
      });
    }

    if (actionTypes.send_whatsapp) {
      templates.push({
        id: "pro_whatsapp_notification",
        name: "Booking Confirmed -> WhatsApp Notification",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: WhatsApp notification",
        actions: [
          {
            type: "send_whatsapp",
            status: "active",
            config: {
              account_sid: "",
              auth_token: "",
              from: "whatsapp:",
              to: "whatsapp:{{customer_phone}}",
              body: "Your booking for {{service_name}} is confirmed for {{start_date}} at {{start_time}}.",
            },
          },
        ],
      });
    }

    if (actionTypes.mailchimp_subscribe) {
      templates.push({
        id: "pro_mailchimp_sync",
        name: "Booking Created -> Mailchimp Audience Sync",
        event_key: "booking_created",
        workflow_name: "Booking Created: Mailchimp sync",
        actions: [
          {
            type: "mailchimp_subscribe",
            status: "active",
            config: {
              api_key: "",
              audience_id: "",
              email: "{{customer_email}}",
              status: "subscribed",
              first_name: "{{customer_name}}",
              last_name: "",
              tags: "BookPoint",
            },
          },
        ],
      });
    }

    if (actionTypes.hubspot_upsert_contact) {
      templates.push({
        id: "pro_hubspot_sync",
        name: "Booking Created -> HubSpot Contact Sync",
        event_key: "booking_created",
        workflow_name: "Booking Created: HubSpot sync",
        actions: [
          {
            type: "hubspot_upsert_contact",
            status: "active",
            config: {
              access_token: "",
              email: "{{customer_email}}",
              firstname: "{{customer_name}}",
              lastname: "",
              phone: "{{customer_phone}}",
              properties: "bookpoint_last_booking_id={{booking_id}}\nbookpoint_last_service={{service_name}}",
            },
          },
        ],
      });
    }

    if (actionTypes.crm_webhook) {
      templates.push({
        id: "pro_crm_webhook",
        name: "Booking Created -> CRM Webhook",
        event_key: "booking_created",
        workflow_name: "Booking Created: CRM webhook",
        actions: [
          {
            type: "crm_webhook",
            status: "active",
            config: {
              url: "",
              secret: "",
              headers: "",
            },
          },
        ],
      });
    }

    return templates;
  }, [actionTypes]);

  const integrationTemplates = useMemo(() => {
    const templates = [];

    if (actionTypes.google_calendar_sync) {
      templates.push({
        id: "pro_google_calendar_sync",
        name: "Booking Created -> Google Calendar Sync",
        event_key: "booking_created",
        workflow_name: "Booking Created: Google Calendar sync",
        actions: [{ type: "google_calendar_sync", status: "active", config: {} }],
      });
    }

    if (actionTypes.outlook_calendar_sync) {
      templates.push({
        id: "pro_outlook_calendar_sync",
        name: "Booking Created -> Outlook / Microsoft 365 Sync",
        event_key: "booking_created",
        workflow_name: "Booking Created: Outlook sync",
        actions: [{ type: "outlook_calendar_sync", status: "active", config: {} }],
      });
    }

    if (actionTypes.google_meet_link) {
      templates.push({
        id: "pro_google_meet_link",
        name: "Booking Confirmed -> Google Meet Link",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: Google Meet link",
        actions: [{ type: "google_meet_link", status: "active", config: {} }],
      });
    }

    if (actionTypes.zoom_meeting_create) {
      templates.push({
        id: "pro_zoom_meeting_create",
        name: "Booking Confirmed -> Zoom Meeting Link",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: Zoom meeting link",
        actions: [{ type: "zoom_meeting_create", status: "active", config: {} }],
      });
    }

    return templates;
  }, [actionTypes]);

  const revenueTemplates = useMemo(() => {
    const templates = [];

    if (actionTypes.create_recurring_appointments) {
      templates.push({
        id: "pro_recurring_appointments",
        name: "Booking Confirmed -> Create Recurring Appointments",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: recurring appointments",
        actions: [{ type: "create_recurring_appointments", status: "active", config: {} }],
      });
    }

    if (actionTypes.create_package_purchase) {
      templates.push({
        id: "pro_package_purchase",
        name: "Booking Confirmed -> Create Package Purchase",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: package purchase",
        actions: [{ type: "create_package_purchase", status: "active", config: {} }],
      });
    }

    if (actionTypes.redeem_package_credit) {
      templates.push({
        id: "pro_redeem_package_credit",
        name: "Booking Confirmed -> Redeem Package Credit",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: redeem package credit",
        actions: [{ type: "redeem_package_credit", status: "active", config: {} }],
      });
    }

    if (actionTypes.create_deposit_payment_link) {
      templates.push({
        id: "pro_deposit_payment_link",
        name: "Booking Created -> Deposit / Partial Payment Link",
        event_key: "booking_created",
        workflow_name: "Booking Created: deposit payment link",
        actions: [{ type: "create_deposit_payment_link", status: "active", config: {} }],
      });
    }

    if (actionTypes.create_invoice) {
      templates.push({
        id: "pro_create_invoice",
        name: "Booking Confirmed -> Create Invoice",
        event_key: "booking_confirmed",
        workflow_name: "Booking Confirmed: create invoice",
        actions: [{ type: "create_invoice", status: "active", config: {} }],
      });
    }

    if (actionTypes.create_payment_link) {
      templates.push({
        id: "pro_create_payment_link",
        name: "Booking Created -> Create Payment Link",
        event_key: "booking_created",
        workflow_name: "Booking Created: payment link",
        actions: [{ type: "create_payment_link", status: "active", config: {} }],
      });
    }

    if (actionTypes.refund_payment) {
      templates.push({
        id: "pro_refund_payment",
        name: "Booking Cancelled -> Refund Management",
        event_key: "booking_cancelled",
        workflow_name: "Booking Cancelled: refund payment",
        actions: [{ type: "refund_payment", status: "active", config: {} }],
      });
    }

    return templates;
  }, [actionTypes]);

  async function addFromTemplate(tpl) {
    setError("");
    setBusyId(tpl.id);
    try {
      const resp = await bpFetch("/admin/notifications/workflows", {
        method: "POST",
        body: {
          name: tpl.workflow_name || tpl.name || "New workflow",
          event_key: tpl.event_key,
          status: "active",
        },
      });
      const workflowId = resp?.data?.id;
      if (!workflowId) throw new Error("Could not create workflow.");

      for (const a of tpl.actions || []) {
        await bpFetch(`/admin/notifications/workflows/${workflowId}/actions`, {
          method: "POST",
          body: { type: a.type || "send_email", status: a.status || "active", config: a.config || {} },
        });
      }

      setTemplatesOpen(false);
      setTick((prev) => prev + 1);
      showToast("Template added.");
      openEditor(workflowId);
    } catch (err) {
      setError(err.message || "Could not add template.");
    } finally {
      setBusyId(null);
    }
  }

  const workflowsCount = workflows.length;
  const totalCapabilityCount = capabilityGroups.reduce((sum, group) => sum + group.totalCount, 0);
  const totalReadyCount = capabilityGroups.reduce((sum, group) => sum + group.readyCount, 0);

  const renderTemplateCard = (tpl) => (
    <div key={tpl.id} className="bp-notif-template-card">
      <div className="bp-notif-template-card__title">{tpl.name}</div>
      <div className="bp-notif-template-card__meta">
        Event: {EVENT_LABELS[tpl.event_key] || tpl.event_key} - {tpl.actions.length} action(s)
      </div>
      <div className="bp-notif-template-card__actions">
        <button className="bp-btn bp-btn-primary" disabled={busyId === tpl.id} onClick={() => addFromTemplate(tpl)}>
          {busyId === tpl.id ? "Adding..." : "Use template"}
        </button>
      </div>
    </div>
  );

  return (
    <div className="bp-content bp-notif-screen">
      {toast ? <div className="bp-toast bp-toast-success">{toast}</div> : null}

      <div className="bp-page-head">
        <div>
          <div className="bp-h1">Notifications</div>
          <div className="bp-muted">Automate emails and workflow actions for events.</div>
        </div>
        <div className="bp-head-actions">
          <button className="bp-btn" onClick={() => setTemplatesOpen(true)}>
            Templates
          </button>
          <button className="bp-primary-btn" onClick={addWorkflow}>
            + Add workflow
          </button>
        </div>
      </div>

      {!!error && <div className="bp-error">{error}</div>}

      <div className="bp-card bp-notif-coverage">
        <div className="bp-notif-coverage__head">
          <div className="bp-notif-coverage__intro">
            <div className="bp-section-title bp-notif-coverage__title">Pro Capability Coverage</div>
            <div className="bp-muted bp-text-sm">
              {proActive
                ? "All Pro capability groups are checked against feature flags and available workflow action types."
                : "Install and activate BookPoint Pro to unlock all capability groups listed below."}
            </div>
          </div>
          <div className="bp-notif-coverage__badges">
            <span className={`bp-badge ${proActive ? "paid" : "pending_payment"}`}>{proActive ? "Pro active" : "Pro required"}</span>
            <span className="bp-badge completed">
              {totalReadyCount}/{totalCapabilityCount} ready
            </span>
          </div>
        </div>

        <div className="bp-notif-coverage__groups">
          {capabilityGroups.map((group) => (
            <section key={group.title} className="bp-notif-coverage__group">
              <div className="bp-notif-coverage__groupHead">
                <div>
                  <div className="bp-font-900">{group.title}</div>
                  <div className="bp-muted bp-text-xs bp-notif-coverage__groupLead">
                    {group.lead}
                  </div>
                </div>
                <span className={`bp-badge ${group.readyCount === group.totalCount ? "paid" : "pending_payment"}`}>
                  {group.readyCount}/{group.totalCount} ready
                </span>
              </div>

              <div className="bp-notif-coverage__items">
                {group.items.map((item) => (
                  <div key={`${group.title}-${item.key}-${item.label}`} className="bp-notif-coverage__item">
                    <div className="bp-font-800">{item.label}</div>
                    <div className="bp-muted bp-text-xs bp-notif-coverage__itemText">
                      {item.description}
                    </div>
                    <div className="bp-notif-coverage__itemFooter">
                      <span className={`bp-badge ${item.ready ? "paid" : "pending_payment"}`}>
                        {item.ready ? "Ready" : "Not ready"}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          ))}
        </div>
      </div>

      <ProContextCard
        eyebrow="Automation Limits"
        title="Need workflow channels beyond core email notifications?"
        description="This screen already covers the event model. Pro adds the outbound channels, sync actions, and revenue automations teams usually need once bookings become operational."
        bullets={[
          "Signed webhooks, SMS reminders, WhatsApp notifications, and CRM sync actions.",
          "Google Calendar, Outlook / Microsoft 365, Zoom, and Google Meet workflow actions.",
          "Recurring bookings, packages, deposits, invoices, payment links, and refund workflows.",
        ]}
        proTab="automation"
        primaryLabel="See Automation Upgrade"
      />

      <div className="bp-card bp-notif-toolbar">
        <div className="bp-notif-toolbar__search">
          <input
            className="bp-input"
            placeholder="Search workflows..."
            value={search}
            onChange={(event) => setSearch(event.target.value)}
          />
        </div>

        <div className="bp-notif-toolbar__filters">
          <select className="bp-input" value={statusFilter} onChange={(event) => setStatusFilter(event.target.value)}>
            <option value="all">Status: All</option>
            <option value="active">Active</option>
            <option value="disabled">Disabled</option>
          </select>

          <button className="bp-btn bp-btn-ghost" onClick={loadWorkflows}>
            Refresh
          </button>
        </div>

        <div className="bp-notif-toolbar__meta">
          {loading ? "Loading..." : `${workflowsCount} workflows`}
        </div>

        <div className="bp-notif-toolbar__chips">
          <div className="bp-notif-toolbar__chipList">
            <button
              type="button"
              className={`bp-chip-btn ${eventFilter === "" ? "is-active" : ""}`}
              onClick={() => setEventFilter("")}
            >
              All
            </button>
            {(meta.events || Object.keys(EVENT_LABELS)).map((ev) => (
              <button
                key={ev}
                type="button"
                className={`bp-chip-btn ${eventFilter === ev ? "is-active" : ""}`}
                onClick={() => setEventFilter(ev)}
              >
                {EVENT_LABELS[ev] || ev}
                {meta.counts?.[ev]?.total ? <span className="bp-muted bp-notif-toolbar__chipCount">({meta.counts[ev].total})</span> : null}
              </button>
            ))}
          </div>
        </div>
      </div>

      {loading ? (
        <div className="bp-card bp-notif-state bp-state-card bp-state-card--inline">Loading workflows...</div>
      ) : workflowsCount === 0 ? (
        <div className="bp-card bp-notif-state bp-state-card bp-state-card--inline">No workflows yet. Use "+ Add workflow" to get started.</div>
      ) : (
        <div className="bp-notif-list">
          {workflows.map((workflow) => (
            <article
              key={workflow.id}
              className="bp-card bp-notif-row"
            >
              <div className="bp-notif-row__main">
                <div className="bp-notif-row__title">
                  {workflow.name || `Workflow #${workflow.id}`}
                </div>
                <div className="bp-notif-row__event">
                  {(EVENT_LABELS[workflow.event_key] || workflow.event_key) ?? "Event"} - {workflow.event_key}
                </div>

                <div className="bp-notif-row__meta">
                  <span className={`bp-ff-pill ${workflow.status === "active" ? "bp-ff-pill--req" : "bp-ff-pill--off"}`}>
                    {workflow.status === "active" ? "Active" : "Disabled"}
                  </span>
                  <span className="bp-notif-row__metaItem">
                    {workflow.actions_count ?? 0} {workflow.actions_count === 1 ? "action" : "actions"}
                  </span>
                  <span className="bp-notif-row__metaItem">
                    {workflow.last_run_at
                      ? `Last run: ${new Date(workflow.last_run_at).toLocaleString()}${workflow.last_run_status ? ` (${workflow.last_run_status})` : ""}`
                      : "Last run: Never"}
                  </span>
                </div>
              </div>

              <div className="bp-notif-row__actions">
                <button
                  type="button"
                  className={`bp-btn-sm ${workflow.status === "active" ? "" : "bp-btn-danger"}`}
                  disabled={busyId === workflow.id}
                  onClick={() => toggleWorkflowStatus(workflow)}
                >
                  {workflow.status === "active" ? "Disable" : "Enable"}
                </button>

                <button className="bp-btn" disabled={busyId === workflow.id} onClick={() => testWorkflow(workflow.id)}>
                  Test
                </button>

                <button className="bp-btn" onClick={() => openEditor(workflow.id)}>
                  Edit
                </button>

                <button
                  type="button"
                  className="bp-btn bp-btn-danger"
                  disabled={busyId === workflow.id}
                  onClick={() => deleteWorkflow(workflow)}
                >
                  Delete
                </button>
              </div>
            </article>
          ))}
        </div>
      )}

      {templatesOpen ? (
        <Modal
          open={templatesOpen}
          title="Templates"
          subtitle="Quick-start templates for notifications, integrations, and revenue workflows."
          onClose={() => setTemplatesOpen(false)}
          width="900px"
        >
          <div className="bp-notif-templates">
            <div className="bp-notif-template-grid">
              {baseTemplates.map((tpl) => renderTemplateCard(tpl))}
            </div>

            {automationTemplates.length > 0 ? (
              <>
                <div className="bp-notif-templates__sectionTitle">Automation Templates (Pro)</div>
                <div className="bp-text-xs bp-muted bp-notif-templates__sectionLead">
                  Advanced webhooks, SMS, WhatsApp, and Mailchimp/CRM starter flows.
                </div>
                <div className="bp-notif-template-grid">
                  {automationTemplates.map((tpl) => renderTemplateCard(tpl))}
                </div>
              </>
            ) : null}

            {integrationTemplates.length > 0 ? (
              <>
                <div className="bp-notif-templates__sectionTitle">Integration Templates (Pro)</div>
                <div className="bp-text-xs bp-muted bp-notif-templates__sectionLead">
                  Google Calendar, Microsoft 365, Zoom, and Google Meet starter flows.
                </div>
                <div className="bp-notif-template-grid">
                  {integrationTemplates.map((tpl) => renderTemplateCard(tpl))}
                </div>
              </>
            ) : null}

            {revenueTemplates.length > 0 ? (
              <>
                <div className="bp-notif-templates__sectionTitle">Revenue Templates (Pro)</div>
                <div className="bp-text-xs bp-muted bp-notif-templates__sectionLead">
                  Recurring appointments, packages, deposits, invoices, payment links, and refunds.
                </div>
                <div className="bp-notif-template-grid">
                  {revenueTemplates.map((tpl) => renderTemplateCard(tpl))}
                </div>
              </>
            ) : null}

            {automationTemplates.length === 0 && integrationTemplates.length === 0 && revenueTemplates.length === 0 ? (
              <div className="bp-text-sm bp-muted bp-notif-templates__empty">
                Pro templates appear automatically when BookPoint Pro action types are available.
              </div>
            ) : null}
          </div>
        </Modal>
      ) : null}

      {showEditor && selectedId ? <WorkflowEditScreen workflowId={selectedId} onClose={closeEditor} onSaved={() => setTick((prev) => prev + 1)} /> : null}
    </div>
  );
}
