// Modals.jsx — Template detail + Starter pack modals.

const CloseIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <line x1="18" y1="6" x2="6" y2="18" />
    <line x1="6" y1="6" x2="18" y2="18" />
  </svg>;

const PlayIcon = () =>
<svg viewBox="0 0 24 24" fill="currentColor" stroke="none"><polygon points="5 3 19 12 5 21 5 3" /></svg>;

const VideoIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polygon points="23 7 16 12 23 17 23 7" />
    <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />
  </svg>;

const ClickIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M9 9h.01M3 9V5a2 2 0 0 1 2-2h4M3 15v4a2 2 0 0 0 2 2h4" />
    <path d="m13 13 6 6m0-6-6 6" />
  </svg>;

const PackageIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M16.5 9.4 7.55 4.24" /><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
    <polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" />
  </svg>;

const ClockIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" />
  </svg>;


// Destination-type icons for buttons in the Flow Structure section.
// Each indicates where the button leads: another video (arrow right),
// Destination-type icons for buttons in the Flow Structure section.
// Right-arrow = plays next video (orange, warm accent — "flow continues").
// Down-arrow = scrolls to section (teal, neutral brand tone — "stays here").
// Arrow-out-of-box = external link (neutral — "leaves the flow").
const NextVideoIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <line x1="5" y1="12" x2="19" y2="12" />
    <polyline points="12 5 19 12 12 19" />
  </svg>;

const ExternalLinkIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
    <polyline points="15 3 21 3 21 9" />
    <line x1="10" y1="14" x2="21" y2="3" />
  </svg>;

const ScrollToSectionIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <polyline points="6 9 12 15 18 9" />
  </svg>;

// Compact video glyph for the header of each flow block — film/strip icon
// with a play triangle, sized to sit inside the same warm squircle as the
// destination icons so the whole row reads as one consistent set.
const VideoFilmIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="3" y="6" width="18" height="12" rx="2" />
    <polygon points="11 9.5 15 12 11 14.5 11 9.5" fill="currentColor" stroke="none" />
  </svg>;


const outcomeMap = {
  "Increase Event Registrations": "Capture Early Visitor Interest",
  "Re-engage Past Delegates": "Bring back previous attendees with personalised outreach",
  "Attract and Retain Sponsors": "Guide potential sponsors to the right partnership tier",
  "Drive Exhibitor Stand Traffic": "Route attendees to exhibitor stands that match their interests",
  "Showcase My Speakers": "Highlight your speaker lineup and drive session sign-ups",
  "Serve Every Audience from One Page": "Create one landing page that serves sponsors, exhibitors and attendees",
  "Tell My Event Story": "Walk visitors through your event narrative with interactive video",
  "Help Delegates Get Internal Sign-off": "Give attendees the tools to justify their ticket internally",
  "Reduce Delegate No-shows": "Keep registrants engaged and committed before event day",
  "Help Exhibitors Convert Visits into Pipeline": "Turn stand visitors into qualified leads and meetings",
  "Give Sponsors Measurable ROI": "Provide sponsors with trackable engagement and lead data",
  "Build My Event Community Year-round": "Keep your audience engaged between events with ongoing content"
};

const descriptionMap = {
  "Increase Event Registrations": "Use this on your homepage from the moment registration opens for next year, typically around 10–12 months out. Route attendees, exhibitors, and press to the content that matters to them. Acts as a friendly, human front door that cuts bounce rates and drives deeper engagement long before your agenda is ready.",
  "Re-engage Past Delegates": "Win back previous attendees by showing them what's new and why this year is unmissable. Personalised paths based on their previous attendance.",
  "Attract and Retain Sponsors": "Walk potential sponsors through your value proposition, audience demographics, and package options — automatically routed to the right tier.",
  "Drive Exhibitor Stand Traffic": "Help attendees discover exhibitors that match their interests using a short quiz that recommends stands and books meetings before the event.",
  "Showcase My Speakers": "Create an engaging speaker showcase that lets visitors explore sessions, watch speaker previews, and add sessions to their agenda.",
  "Serve Every Audience from One Page": "One landing page, three audiences. Detects whether someone is a sponsor, exhibitor, or attendee and routes them to the right content automatically.",
  "Tell My Event Story": "Transform your event marketing into an immersive video narrative. Walk visitors through highlights, testimonials, and key moments that build excitement.",
  "Help Delegates Get Internal Sign-off": "Provide attendees with a shareable business case, ROI calculator, and manager email template — everything they need to get approval to attend.",
  "Reduce Delegate No-shows": "Keep registrants engaged with countdown content, agenda previews, and personalised reminders that maintain excitement through to event day.",
  "Help Exhibitors Convert Visits into Pipeline": "Give exhibitors interactive tools to capture leads, qualify visitors, and book follow-up meetings — all tracked in one dashboard.",
  "Give Sponsors Measurable ROI": "Provide sponsors with real-time engagement data, lead capture tools, and branded interactive experiences that prove their ROI.",
  "Build My Event Community Year-round": "Keep your audience engaged between events with ongoing video content, community challenges, and early-access previews."
};

// Each video block in the flow is one entry. Buttons under a video have a
// `kind` describing where they lead — "next-video" (plays another video in
// this flow, with a `target` index), "external" (opens a URL), or "scroll"
// (scrolls to a section on the current page). The same shape works for a
// 1-video template (one block, a few buttons, no targets) and a 6-video
// branching template (six stacked blocks, buttons that point at each other).
const generateFlow = (steps, templateTitle) => {
  // Per-template flows — keyed by title. Default fallback below.
  if (templateTitle === "Increase Event Registrations") {
    return [
    { name: "A warm, generic welcome to the event with a quick pitch for why someone might be here.", buttons: [
      { label: "I want to attend", kind: "next-video", target: 1 },
      { label: "I want to exhibit", kind: "next-video", target: 2 },
      { label: "Last year's highlights", kind: "next-video", target: 3 }]
    },
    { name: "A short pitch on what the event is, who it's for, and what attendees take away.", buttons: [
      { label: "Last year's highlights", kind: "next-video", target: 3 },
      { label: "Register Interest", kind: "external" }]
    },
    { name: "A short pitch on the audience exhibitors will reach and the commercial case for being on the floor.", buttons: [
      { label: "Sales pack", kind: "external" },
      { label: "Last year's highlights", kind: "next-video", target: 3 },
      { label: "Book a call", kind: "external" }]
    },
    { name: "A 30–60 second sizzle reel of last year's event – energy, scale, key moments.", buttons: [
      { label: "Sales pack", kind: "external" },
      { label: "I want to attend", kind: "next-video", target: 1 },
      { label: "I want to exhibit", kind: "next-video", target: 2 }]
    }];
  }
  const all = [
  { name: "Who are you?", buttons: [
    { label: "I want to attend", kind: "next-video", target: 1 },
    { label: "I'm a sponsor", kind: "next-video", target: 2 },
    { label: "I'm an exhibitor", kind: "next-video", target: 3 }]
  },
  { name: "Attending the event", buttons: [
    { label: "Register today", kind: "external" },
    { label: "View the agenda", kind: "scroll" },
    { label: "Back to start", kind: "next-video", target: 0 }]
  },
  { name: "Sponsor opportunities", buttons: [
    { label: "Download sponsor pack", kind: "external" },
    { label: "Book a meeting", kind: "external" },
    { label: "Back to start", kind: "next-video", target: 0 }]
  },
  { name: "Exhibitor information", buttons: [
    { label: "Reserve a stand", kind: "external" },
    { label: "Floor plan", kind: "scroll" },
    { label: "Back to start", kind: "next-video", target: 0 }]
  },
  { name: "Event agenda", buttons: [
    { label: "Day 1 sessions", kind: "scroll" },
    { label: "Full programme", kind: "external" }]
  }];

  return all.slice(0, Math.min(steps, all.length));
};

function TemplateDetailModal({ template, onClose, related = [], onUse, onOpenRelated }) {
  if (!template) return null;
  // Manifest-driven: videos & buttons live on the template object directly.
  // Each button has { label, destination } where destination is either
  // a video id ("V2") or "URL" for an external link.
  const videos = template.videos || [];
  const variant = Math.max(0, Math.min(5, (videos.length || 1) - 1));
  const phaseDef = (window.PHASES || []).find((p) => p.id === template.phase);
  const pageLabel = (window.PAGES || {})[template.page] || null;
  const audienceLabel = (window.AUDIENCES || {})[template.audience] || null;

  // Build a lookup so we can render "plays Video 2" instead of "plays V2".
  // Vn ids are 1-indexed in the manifest; we display them the same way.
  const videoIndex = {};
  videos.forEach((v, i) => { videoIndex[v.id] = i + 1; });

  React.useEffect(() => {
    const onKey = (e) => {if (e.key === "Escape") onClose();};
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {document.removeEventListener("keydown", onKey);document.body.style.overflow = "";};
  }, [onClose]);

  return (
    <div className="tb-modal-backdrop" onClick={onClose}>
      <div className="tb-modal" onClick={(e) => e.stopPropagation()}>
        <button className="tb-modal__close" onClick={onClose} aria-label="Close"><CloseIcon /></button>

        <div className="tb-modal__top">
          <div className="tb-modal__visual">
            <FlowThumbnail variant={variant} />
          </div>
          <div className="tb-modal__info">
            <div className="tb-modal__chips">
              {phaseDef && <span className={"tb-modal__chip is-phase is-phase-" + template.phase}>{phaseDef.label}</span>}
            </div>
            <h2 className="tb-modal__title">{template.title}</h2>
            <p className="tb-modal__desc">{template.description}</p>
            <p className="tb-modal__attribution">
              {pageLabel || "—"}{audienceLabel ? " · " + (template.audience === "all" ? "All audiences" : audienceLabel) : ""}
            </p>
            <div className="tb-modal__ctas">
              <button className="rf-btn rf-btn--secondary" onClick={onUse}>Use This Template</button>
            </div>
          </div>
        </div>

        <div className="tb-modal__body">
          <section className="tb-modal__section">
            <h3>Flow Structure</h3>
            <p className="tb-flow-helper">This is the starting structure — every video, button, and destination is editable once you load the template into your workspace.</p>
            <div className="tb-flow-list">
              {videos.map((video, i) =>
              <div className="tb-flow-video" key={video.id || i}>
                  <div className="tb-flow-video__head">
                    <span className="tb-flow-video__glyph" aria-hidden="true"><VideoFilmIcon /></span>
                    <div className="tb-flow-video__heading">
                      <span className="tb-flow-video__num">Video {i + 1}</span>
                      <span className="tb-flow-video__name">{video.title}</span>
                    </div>
                  </div>
                  {video.buttons && video.buttons.length > 0 ?
                  <ul className="tb-flow-video__buttons">
                    {video.buttons.map((b, j) => {
                      const isExternal = b.destination === "URL";
                      const Icon = isExternal ? ExternalLinkIcon : NextVideoIcon;
                      const kind = isExternal ? "external" : "next-video";
                      const targetNum = !isExternal ? videoIndex[b.destination] : null;
                      return (
                        <li key={j} className={"tb-flow-bullet is-" + kind}>
                            <span className="tb-flow-bullet__icon" aria-hidden="true"><Icon /></span>
                            <span className="tb-flow-bullet__label">{b.label}</span>
                            <span className="tb-flow-bullet__sep" aria-hidden="true">—</span>
                            {isExternal ?
                            <span className="tb-flow-bullet__target">opens external link</span> :
                            <span className="tb-flow-bullet__target">plays Video {targetNum || "?"}</span>
                            }
                          </li>);
                    })}
                  </ul> :
                  <p className="tb-flow-video__no-buttons">No buttons — viewers just watch and exit.</p>
                  }
                </div>
              )}
            </div>
          </section>

          {related.length > 0 &&
          <section className="tb-modal__section">
              <h3>More like this</h3>
              <p className="meta">Other templates in the same phase</p>
              <div className="tb-related">
                {related.slice(0, 3).map((rt, i) =>
              <UseCaseCard
                key={rt.id}
                {...rt}
                variant={(i + 2) % 6}
                onClick={() => onOpenRelated && onOpenRelated(rt, (i + 2) % 6)}
                onUseTemplate={onUse} />

              )}
              </div>
            </section>
          }
        </div>
      </div>
    </div>);

}

const packTemplatesMap = {
  "Event Organiser Starter Pack": [
  { name: "Event Homepage Hero Flow", outcome: "Convert landing page visitors into registrations", steps: 4, variant: 0 },
  { name: "Ticket Selector", outcome: "Recommend the right ticket based on answers", steps: 3, variant: 1 },
  { name: "Speaker Showcase", outcome: "Highlight speakers and drive session sign-ups", steps: 3, variant: 2 },
  { name: "Agenda Explorer", outcome: "Help attendees plan their day interactively", steps: 4, variant: 3 },
  { name: "Early Bird Countdown", outcome: "Create urgency around early pricing deadlines", steps: 2, variant: 4 },
  { name: "Venue Tour", outcome: "Walk visitors through the event space virtually", steps: 3, variant: 5 },
  { name: "FAQ Navigator", outcome: "Answer common questions with branching video", steps: 3, variant: 0 },
  { name: "Registration Confirmation", outcome: "Onboard new registrants with next steps", steps: 2, variant: 1 },
  { name: "Multi-track Selector", outcome: "Guide attendees to the right conference track", steps: 4, variant: 2 },
  { name: "Social Proof Reel", outcome: "Show testimonials from past attendees", steps: 3, variant: 3 },
  { name: "Group Booking Flow", outcome: "Simplify team and group registrations", steps: 4, variant: 4 },
  { name: "Post-Event Feedback", outcome: "Gather feedback and offer an upsell", steps: 3, variant: 5 }],

  "Sponsor Pack": [
  { name: "Sponsor Qualification", outcome: "Route sponsors to the right package tier", steps: 5, variant: 1 },
  { name: "Package Comparison", outcome: "Help sponsors compare sponsorship options", steps: 3, variant: 4 },
  { name: "ROI Calculator", outcome: "Show sponsors their expected return on investment", steps: 4, variant: 2 },
  { name: "Sponsor Onboarding", outcome: "Collect assets and details from confirmed sponsors", steps: 3, variant: 0 },
  { name: "Lead Capture Setup", outcome: "Configure sponsor lead capture before the event", steps: 3, variant: 5 },
  { name: "Sponsor Showcase", outcome: "Feature sponsors with interactive branded content", steps: 2, variant: 3 },
  { name: "Post-Event Sponsor Report", outcome: "Deliver engagement metrics to sponsors", steps: 3, variant: 1 },
  { name: "Sponsor Renewal Flow", outcome: "Re-engage sponsors for next year's event", steps: 4, variant: 4 }],

  "Exhibitors Pack": [
  { name: "Exhibitor Onboarding", outcome: "Collect exhibitor details before the event", steps: 3, variant: 2 },
  { name: "Stand Traffic Driver", outcome: "Route attendees to relevant exhibitor stands", steps: 4, variant: 5 },
  { name: "Lead Scanner Setup", outcome: "Set up exhibitor lead capture tools", steps: 2, variant: 0 },
  { name: "Product Demo Flow", outcome: "Guide stand visitors through a product demo", steps: 4, variant: 3 },
  { name: "Meeting Booker", outcome: "Let visitors book meetings at the stand", steps: 3, variant: 1 },
  { name: "Exhibitor Directory", outcome: "Help attendees discover and filter exhibitors", steps: 3, variant: 4 },
  { name: "Post-Event Follow-up", outcome: "Automate exhibitor follow-up with leads", steps: 3, variant: 2 },
  { name: "Exhibitor Feedback", outcome: "Gather exhibitor satisfaction data", steps: 2, variant: 5 },
  { name: "Stand Design Preview", outcome: "Show exhibitors their stand layout options", steps: 3, variant: 0 },
  { name: "Exhibitor ROI Summary", outcome: "Summarise leads and engagement for exhibitors", steps: 3, variant: 3 }],

  "Attendees Pack": [
  { name: "Welcome & Orientation", outcome: "Onboard attendees when they arrive", steps: 3, variant: 3 },
  { name: "Networking Matcher", outcome: "Pair attendees based on interests", steps: 4, variant: 1 },
  { name: "Session Recommender", outcome: "Suggest sessions based on attendee profile", steps: 3, variant: 4 },
  { name: "VIP Experience Upgrade", outcome: "Offer premium add-ons mid-flow", steps: 3, variant: 0 },
  { name: "Delegate Sign-off Helper", outcome: "Give tools to justify attendance internally", steps: 4, variant: 2 },
  { name: "Event App Walkthrough", outcome: "Guide attendees through the event app", steps: 2, variant: 5 },
  { name: "No-show Prevention", outcome: "Keep registrants engaged before event day", steps: 3, variant: 3 },
  { name: "Feedback & NPS", outcome: "Collect attendee feedback post-event", steps: 3, variant: 1 },
  { name: "Content On-demand", outcome: "Let attendees access session recordings", steps: 4, variant: 4 }]

};

function StarterPackModal({ pack, onClose, onLoadAll }) {
  if (!pack) return null;
  const [expandedIdx, setExpandedIdx] = React.useState(null);
  // Pack shape now: { name, phaseId, description, window, templates: [manifest templates] }
  // Fall back to the old hard-coded map if a legacy pack is passed in.
  const manifestTemplates = pack.templates || [];
  const legacyTemplates = packTemplatesMap[pack.name] || [];
  const usingManifest = manifestTemplates.length > 0;
  const templates = usingManifest
    ? manifestTemplates.map((t, i) => ({
        name: t.title,
        outcome: (window.PAGES || {})[t.page] || "",
        description: t.description || "",
        steps: (t.videos || []).length,
        variant: Math.max(0, Math.min(5, ((t.videos || []).length || 1) - 1))
      }))
    : legacyTemplates;
  const totalSteps = templates.reduce((s, t) => s + t.steps, 0);
  const totalButtons = usingManifest
    ? manifestTemplates.reduce((s, t) => s + (t.videos || []).reduce((bs, v) => bs + (v.buttons || []).length, 0), 0)
    : templates.reduce((s, t) => s + t.steps * 3, 0);

  React.useEffect(() => {
    const onKey = (e) => {if (e.key === "Escape") onClose();};
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {document.removeEventListener("keydown", onKey);document.body.style.overflow = "";};
  }, [onClose]);

  return (
    <div className="tb-modal-backdrop" onClick={onClose}>
      <div className="tb-modal" onClick={(e) => e.stopPropagation()}>
        <button className="tb-modal__close" onClick={onClose} aria-label="Close"><CloseIcon /></button>

        <div className="tb-pack-modal__head">
          <div className="tb-pack-modal__head-row">
            <div>
              <div className="tb-pack-modal__icon-wrap" style={{ color: "var(--rf-yellow-800)" }}>
                <PackageIcon />
              </div>
              <h2 className="tb-modal__title" style={{ marginBottom: ".5rem" }}>{pack.name}</h2>
              <p className="tb-modal__desc" style={{ maxWidth: "32rem" }}>{pack.description}</p>
            </div>
            <button className="rf-btn rf-btn--secondary" style={{ flex: "none" }} onClick={onLoadAll}>
              Load All {templates.length} Templates
            </button>
          </div>
        </div>

        <div className="tb-pack-modal__body">
          <p className="tb-pack-modal__section-label">What's inside · {templates.length} templates</p>
          <div>
            {templates.map((t, i) => {
              const isExpanded = expandedIdx === i;
              return (
              <div className={"tb-pack-template-wrap" + (isExpanded ? " is-expanded" : "")} key={i}>
                <div className={"tb-pack-template" + (isExpanded ? " is-expanded" : "")} onClick={() => setExpandedIdx(isExpanded ? null : i)}>
                  <div className="tb-pack-template__thumb">
                    <FlowThumbnail variant={t.variant} />
                  </div>
                  <div className="tb-pack-template__info">
                    <p className="tb-pack-template__name">{t.name}</p>
                    <p className="tb-pack-template__outcome">{t.outcome}</p>
                  </div>
                  <span className="tb-pack-template__steps">{t.steps} videos</span>
                  <span className="tb-pack-template__expand" aria-hidden="true">
                    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="4 6 8 10 12 6" />
                    </svg>
                  </span>
                </div>
                {isExpanded && t.description &&
                  <p className="tb-pack-template__detail">{t.description}</p>
                }
              </div>);
            })}
          </div>
        </div>

        <div className="tb-pack-modal__footer">
          <p>All {templates.length} templates will be added to your ReelFlow account</p>
          <button className="rf-btn rf-btn--primary" onClick={onLoadAll}>Load All {templates.length} Templates</button>
        </div>
      </div>
    </div>);

}

Object.assign(window, { TemplateDetailModal, StarterPackModal });