/* ================================================================
 * Iteration 2 — Vertical Selector, Trust Strip, Problem, Workflows
 *
 * All four sections exported to window so app.jsx can mount them.
 * Uses the same locked palette (ink/muted/paper/rule/navy/amber) and
 * glass / grid language established in iteration 1.
 * ================================================================ */

/* ---------- Vertical data model ---------- */
const VERTICALS = [
  {
    id: "dental",
    name: "Dental & Orthodontic",
    oneLiner: "Independent and partner-owned practices.",
    problemHeading: "What dental and orthodontic practices are losing every week",
    pains: [
      "New patient inquiries wait 4+ hours for a reply. Many don't wait.",
      "No-shows disappear hours of front desk time every week.",
      "Happy patients leave quietly. Unhappy ones write reviews.",
      "Lapsed patients sit in the PMS. No one reaches out.",
    ],
    workflows: [
      {
        name: "New patient inquiry response",
        desc: "Inbound inquiries across phone, web, and listings are acknowledged within minutes and routed to the front desk with context. The result is captured against a pre-engagement baseline.",
        outcome: "Typical range: 4 to 6 hours of front-desk time recovered per week.",
      },
      {
        name: "Appointment reminder sequence",
        desc: "Multi-channel reminders are sequenced against the PMS schedule, with confirmation state written back. Unresponsive patients surface to the front desk the day prior.",
        outcome: "Typical range: 18 to 32% reduction in no-show rate.",
      },
      {
        name: "Post-visit Google review generation",
        desc: "Review requests are triggered at the highest-signal moment after the visit, on the channel the patient prefers. Sentiment is logged before the public ask.",
        outcome: "Typical range: 3 to 8x increase in monthly review volume.",
      },
      {
        name: "Lapsed patient reactivation",
        desc: "Dormant records are segmented by last-visit interval and risk, then sequenced into clinically appropriate reactivation offers. Reactivations are attributed to the campaign.",
        outcome: "Typical range: 12 to 40 reactivations in the first 90 days.",
      },
    ],
  },
  {
    id: "specialtyMedical",
    name: "Specialty Medical",
    oneLiner: "Dermatology, optometry, PT, chiropractic, med-spas.",
    problemHeading: "What specialty medical practices are losing every week",
    pains: [
      "Specialty care inquiries expect immediate response. Most wait hours.",
      "Missed appointments are lost chair time that never comes back.",
      "Specialty reviews drive referrals more than general practice.",
      "Recall patients stop coming when the recall system stops calling.",
    ],
    workflows: [
      {
        name: "New patient inquiry response",
        desc: "Inquiries are acknowledged within minutes with triage-appropriate information and routed to intake with the source attached. Response latency is logged per channel.",
        outcome: "Typical range: 5 to 8 hours of intake time recovered per week.",
      },
      {
        name: "Appointment reminder and pre-visit instruction sequence",
        desc: "Reminders carry pre-visit prep, arrival instructions, and consent forms. Confirmation state is written back to the scheduling system the day prior.",
        outcome: "Typical range: 22 to 35% reduction in no-show rate.",
      },
      {
        name: "Post-visit review and outcome survey generation",
        desc: "A structured outcome survey is sent after the visit, with the public review ask gated on a positive internal signal. Detractors route to the practice privately.",
        outcome: "Typical range: 4 to 9x increase in monthly review volume.",
      },
      {
        name: "Lapsed patient outreach and recall sequence",
        desc: "Recall intervals are enforced against the EHR. Patients past interval are sequenced back with specialty-appropriate clinical context.",
        outcome: "Typical range: 15 to 45 recalls returned in the first 90 days.",
      },
    ],
  },
  {
    id: "propertyManagement",
    name: "Property Management",
    oneLiner: "Residential and commercial property management firms and HOA management companies.",
    problemHeading: "What property management firms are losing every week",
    pains: [
      "Prospective tenants go dark when inquiries take hours to answer.",
      "Maintenance no-shows and rent-collection calls burn staff time.",
      "Property management reviews are the single biggest signal owners use to choose a firm.",
      "Lease renewal outreach is everyone's job and no one's job.",
    ],
    workflows: [
      {
        name: "New tenant and owner inquiry response",
        desc: "Rental and owner inquiries are acknowledged within minutes, with unit availability and next-step routing. Source and intent are logged for portfolio reporting.",
        outcome: "Typical range: 6 to 10 hours of leasing-staff time recovered per week.",
      },
      {
        name: "Rent collection and maintenance appointment reminders",
        desc: "Rent and maintenance sequences run against the property management system, with confirmation state written back. Escalations route to staff only when required.",
        outcome: "Typical range: 20 to 35% reduction in avoidable collection calls.",
      },
      {
        name: "Google review generation for the management company",
        desc: "Post-resolution requests are triggered at the highest-signal moment for tenants, owners, and vendors on the firm's Google Business profile.",
        outcome: "Typical range: 3 to 7x increase in monthly review volume.",
      },
      {
        name: "Lease renewal and dormant-owner outreach",
        desc: "Renewal windows are enforced from the PMS calendar. Dormant owners are sequenced into a quarterly performance cadence.",
        outcome: "Typical range: 8 to 14% lift in renewal rate.",
      },
    ],
  },
  {
    id: "professionalServices",
    name: "Professional Services",
    oneLiner: "Law firms, CPA firms, financial advisory, and consulting practices.",
    problemHeading: "What professional services firms are losing every week",
    pains: [
      "New client inquiries go to the first firm that replies. Yours replies tomorrow.",
      "Consultation no-shows waste partner-level hours at partner-level rates.",
      "Professional services clients refer more than they review, unless they are asked.",
      "Dormant clients don't call back on their own.",
    ],
    workflows: [
      {
        name: "New matter/client inquiry intake",
        desc: "Inbound inquiries are acknowledged within minutes, pre-qualified against matter type, and routed to the appropriate professional with context attached.",
        outcome: "Typical range: 5 to 9 hours of partner and intake time recovered per week.",
      },
      {
        name: "Consultation and meeting reminder sequences",
        desc: "Consultations and standing meetings are reminded through the sequence most likely to produce a confirmation. Pre-meeting materials are attached.",
        outcome: "Typical range: 25 to 40% reduction in consultation no-shows.",
      },
      {
        name: "Post-engagement review and referral-request generation",
        desc: "At engagement close, clients receive a review ask and a structured referral ask on the channel they used most during the matter.",
        outcome: "Typical range: 3 to 6x increase in referral requests made.",
      },
      {
        name: "Dormant client re-engagement sequence",
        desc: "Prior clients are segmented by matter type and time-since-close, then sequenced into a check-in cadence that surfaces the next engagement opportunity.",
        outcome: "Typical range: 10 to 25 re-engagements in the first 90 days.",
      },
    ],
  },
];

/* Generic (no vertical chosen) content */
const GENERIC_PROBLEM_HEADING = "Every business has tasks that slip through the cracks";
const GENERIC_PAINS = [
  "Your workflow has dozens of small, repeatable tasks: confirmations, follow-ups, handoffs, status checks. Nobody owns them and everyone forgets them.",
  "Inquiries arrive across channels at unpredictable times. Without an instant, consistent response, prospects move on before your team even sees the message.",
  "Appointments, jobs, and consultations fall off the calendar silently. The cost is not just the no-show. It is the dead time your staff cannot reclaim.",
  "Reputation grows one review at a time, but the ask has to land at the exact right moment. Miss that window and the happy client never speaks up.",
  "Client relationships go dormant not because the work was bad, but because no one had 5 minutes to check in. Those relationships compound quietly into lost revenue.",
  "The real problem is not any single task. These micro-gaps are invisible until you map the entire workflow and measure what each one actually costs.",
];
const GENERIC_WORKFLOWS = [
  {
    name: "Real-time inquiry response",
    desc: "Inbound inquiries across every channel are acknowledged within minutes and routed to the right person with context. Response latency is captured against a pre-engagement baseline.",
    outcome: "Typical range: 4 to 8 hours of front-office time recovered per week.",
  },
  {
    name: "Appointment and engagement reminder sequences",
    desc: "Multi-channel reminders run against the firm's scheduling system, with confirmation state written back. Unresponsive contacts surface to staff only when required.",
    outcome: "Typical range: 20 to 35% reduction in no-show rate.",
  },
  {
    name: "Review generation",
    desc: "Review requests are triggered at the highest-signal post-engagement moment. Sentiment is captured internally before the public ask is made.",
    outcome: "Typical range: 3 to 7x increase in monthly review volume.",
  },
  {
    name: "Dormant-relationship reactivation",
    desc: "Dormant records are segmented by last-contact interval and value, then sequenced into appropriate reactivation touches. Results are attributed to the campaign.",
    outcome: "Typical range: 12 to 35 reactivations in the first 90 days.",
  },
];

/* ---------- Small helpers ---------- */
function Eyebrow({ label }) {
  return (
    <div className="flex items-center gap-3 text-[11px] md:text-[12px] uppercase tracking-[0.16em] text-muted">
      <span className="inline-block w-6 h-px bg-navy" aria-hidden="true" />
      <span>{label}</span>
    </div>
  );
}

/* ================================================================
 * 3 — VERTICAL SELECTOR
 * ================================================================ */
function VerticalSelector({ activeId, onSelect }) {
  return (
    <section id="verticals" className="relative border-b border-rule bg-white">
      <div className="max-w-[1200px] mx-auto px-5 md:px-10 py-12 md:py-24">
        <Eyebrow label="Industries" />
        <div className="mt-4 flex flex-col md:flex-row md:items-end md:justify-between gap-4">
          <h2 className="text-[28px] md:text-[40px] leading-[1.05] tracking-tightest font-medium text-ink max-w-[28ch]">
            AEI adapts to your industry. Select yours to see how it applies.
          </h2>
          <p className="text-[14px] text-muted max-w-[40ch]">
            Choose your industry and the sections below tailor to your firm.
          </p>
        </div>

        <div
          role="radiogroup"
          aria-label="Industry"
          className="mt-10 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3"
        >
          {VERTICALS.map((v) => {
            const active = v.id === activeId;
            return (
              <button
                key={v.id}
                role="radio"
                aria-checked={active}
                onClick={() => onSelect(v.id)}
                className={
                  "vertical-card group relative text-left p-5 md:p-6 rounded-xl bg-white border transition-all duration-300 min-h-[80px] " +
                  (active
                    ? "border-navy shadow-[0_12px_40px_-20px_rgba(30,58,95,0.35)] ring-1 ring-navy/30"
                    : "border-rule hover:border-ink/40 hover:-translate-y-0.5")
                }
              >
                <div className="text-[17px] md:text-[18px] font-medium tracking-tighter2 text-ink">
                  {v.name}
                </div>
                <p className="mt-1.5 text-[13.5px] text-muted leading-[1.5]">
                  {v.oneLiner}
                </p>

                <div className="mt-5 flex items-center justify-end text-[12px]">
                  <span
                    aria-hidden="true"
                    className={
                      "inline-flex items-center gap-1 transition-colors " +
                      (active ? "text-navy" : "text-muted group-hover:text-ink")
                    }
                  >
                    {active ? "Selected" : "Select"}
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
                      <path
                        d="M1 5h8M6 1l4 4-4 4"
                        stroke="currentColor"
                        strokeWidth="1.5"
                      />
                    </svg>
                  </span>
                </div>

                {/* Active accent line */}
                <span
                  aria-hidden="true"
                  className={
                    "absolute left-0 top-0 h-full w-[2px] rounded-l-xl transition-all " +
                    (active ? "bg-navy" : "bg-transparent")
                  }
                />
              </button>
            );
          })}
        </div>

        {/* Clear selection */}
        {activeId && (
          <div className="mt-5">
            <button
              onClick={() => onSelect(null)}
              className="text-[13px] text-muted hover:text-ink underline-offset-4 hover:underline"
            >
              Clear selection
            </button>
          </div>
        )}
      </div>
    </section>
  );
}

function CapacityPip({ total, available }) {
  const pips = Array.from({ length: total });
  return (
    <div className="flex items-center gap-1" aria-hidden="true">
      {pips.map((_, i) => (
        <span
          key={i}
          className={
            "w-1.5 h-1.5 rounded-full " +
            (i < available ? "bg-amber" : "bg-rule")
          }
        />
      ))}
    </div>
  );
}

/* ================================================================
 * 4 — TRUST STRIP
 * ================================================================ */
function TrustStrip() {
  const items = [
    "Based in Phoenix, Arizona",
    "Operator-led implementation",
    "90-day engagements, month-to-month after",
  ];
  return (
    <section className="bg-paper border-b border-rule">
      <div className="max-w-[1200px] mx-auto px-5 md:px-10 py-8 md:py-10">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-y-4 gap-x-8">
          {items.map((t, i) => (
            <div
              key={i}
              className="flex items-center gap-3 text-[13.5px] md:text-[14px] text-muted"
            >
              <span
                aria-hidden="true"
                className="inline-block w-1.5 h-1.5 rounded-full bg-navy/70 shrink-0"
              />
              <span className="text-ink">{t}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ================================================================
 * 5 — THE PROBLEM (vertical-adaptive)
 * ================================================================ */
function Problem({ vertical }) {
  const heading = vertical ? vertical.problemHeading : GENERIC_PROBLEM_HEADING;
  const pains = vertical ? vertical.pains : GENERIC_PAINS;
  return (
    <section id="problem" className="bg-white border-b border-rule">
      <div className="max-w-[1200px] mx-auto px-5 md:px-10 py-12 md:py-24">
        <Eyebrow label="The problem" />
        <h2 className="mt-4 text-[28px] md:text-[40px] leading-[1.05] tracking-tightest font-medium text-ink max-w-[28ch]">
          {heading}
        </h2>
        <p className="mt-4 text-[15px] md:text-[17px] leading-[1.55] text-muted max-w-[60ch]">
          AEI does not start with a product. It starts with your workflow. We audit the specific tasks your team performs every day, identify the ones leaking time and revenue, and build automation around them. These are the patterns we see most often:
        </p>

        <div className="mt-10 md:mt-14 grid grid-cols-1 md:grid-cols-2 gap-x-10 gap-y-6 md:gap-y-8">
          {pains.map((p, i) => (
            <div
              key={i}
              className="border-t border-rule pt-5 md:pt-6"
            >
              <p className="text-[17px] md:text-[19px] leading-[1.45] tracking-tighter2 text-ink max-w-[42ch]">
                {p}
              </p>
            </div>
          ))}
        </div>

        {/* Aggregate pain visual — bar chart of where weekly hours leak */}
        <div className="mt-12 md:mt-16 border border-rule rounded-xl bg-paper/60 p-6 md:p-8">
          <div className="flex items-baseline justify-between">
            <div className="num text-[11px] tracking-[0.18em] text-muted uppercase">
              Where the weekly hours go · pre-engagement audit average
            </div>
            <div className="text-[11px] text-muted num">n = 12 firms</div>
          </div>
          <div className="mt-6 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-5 md:gap-8 items-end">
            {[
              { k: "Inquiry response", v: 4.2 },
              { k: "Reminders / no-shows", v: 3.6 },
              { k: "Review generation", v: 1.8 },
              { k: "Reactivation outreach", v: 2.4 },
              { k: "Status updates / handoffs", v: 1.4 },
              { k: "Other micro-tasks", v: 0.6 },
            ].map((c) => (
              <div key={c.k}>
                <div className="flex items-baseline justify-between">
                  <span className="text-[12.5px] text-ink tracking-tighter2">{c.k}</span>
                  <span className="num text-[12px] text-navy">{c.v} hrs</span>
                </div>
                <div className="mt-2 h-2.5 bg-rule rounded-full overflow-hidden">
                  <div
                    className="h-full bg-navy"
                    style={{ width: `${(c.v / 5) * 100}%` }}
                  />
                </div>
              </div>
            ))}
          </div>
          <div className="mt-5 pt-4 border-t border-rule flex items-baseline justify-between">
            <span className="text-[12.5px] text-muted">
              Total weekly hours lost, average
            </span>
            <span className="num text-[18px] text-amber tracking-tighter2">14.0 hrs</span>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================================================================
 * 6 — THE FOUR WORKFLOWS (vertical-adaptive)
 * ================================================================ */
function Workflows({ vertical }) {
  const workflows = vertical ? vertical.workflows : GENERIC_WORKFLOWS;
  return (
    <section id="workflows" className="bg-paper border-b border-rule relative">
      <div className="max-w-[1200px] mx-auto px-5 md:px-10 py-12 md:py-24">
        <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-4">
          <div>
            <Eyebrow label="The core workflows" />
            <h2 className="mt-4 text-[20px] md:text-[40px] leading-[1.05] tracking-tightest font-medium text-ink max-w-[24ch]">
              The workflows AEI deploys. The Friday report measures them
              all.
            </h2>
          </div>
          {vertical && (
            <div className="text-[12px] uppercase tracking-[0.14em] text-muted">
              Showing {vertical.name} industry
            </div>
          )}
        </div>

        <div className="mt-10 md:mt-14 grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
          {workflows.map((w, i) => (
            <article
              key={i}
              className="group relative bg-white border border-rule rounded-xl p-5 md:p-7 hover:border-ink/30 hover:shadow-[0_14px_40px_-24px_rgba(10,10,10,0.25)] transition-all duration-300"
            >
              <div className="flex items-baseline justify-end">
                <span className="num text-[11px] text-muted tracking-[0.14em]">
                  WORKFLOW
                </span>
              </div>
              <h3 className="mt-4 text-[20px] md:text-[22px] font-medium tracking-tighter2 text-ink">
                {w.name}
              </h3>
              <p className="mt-3 text-[15px] leading-[1.6] text-muted">
                {w.desc}
              </p>
              {/* Per-workflow trend sparkline — illustrative momentum across 6 weeks */}
              <div className="mt-5 -mx-1">
                <window.Sparkline
                  values={[
                    [10, 18, 24, 32, 38, 46],
                    [22, 28, 24, 18, 14, 9],
                    [1, 2, 3, 4, 5, 7],
                    [0, 1, 2, 4, 5, 6],
                  ][i]}
                  accent={i === 0}
                />
                <div className="mt-1 flex justify-between text-[10px] num text-muted uppercase tracking-[0.14em]">
                  <span>W1</span><span>W2</span><span>W3</span><span>W4</span><span>W5</span><span>W6</span>
                </div>
              </div>
              <div className="mt-5 pt-4 border-t border-rule flex items-start gap-3">
                <svg
                  className="mt-0.5 shrink-0 text-navy"
                  width="14"
                  height="14"
                  viewBox="0 0 14 14"
                  fill="none"
                  aria-hidden="true"
                >
                  <path
                    d="M1 7l4 4 8-9"
                    stroke="currentColor"
                    strokeWidth="1.5"
                  />
                </svg>
                <span className="text-[13.5px] leading-[1.5] text-ink">
                  {w.outcome}
                </span>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* Export to global so app.jsx can consume */
Object.assign(window, {
  VERTICALS,
  VerticalSelector,
  TrustStrip,
  Problem,
  Workflows,
});
