const { useEffect, useRef, useState } = React;

const CALENDLY = 'https://calendly.com/yachtmarketing/rbyachtmarketing';
const PLAYBOOK = '/playbook';
// Revert HERO_MODE to 'original' to restore the preserved hero-yacht asset.
const ORIGINAL_HERO_ASSET = '/assets/hero-yacht.png';
const CLEAN_HERO_ASSET = '/assets/hero-yacht-clean-v2.png?v=20260723-2';
const HERO_MODE = 'clean-network';

const problems = [
  {
    kicker: 'For Builders',
    title: 'Your in-house marketer is drowning.',
    body: "They're juggling dealer support, sales enablement, model launches and brand consistency. Strategy isn't happening. And your models launch like every other boat.",
    need: 'You need CMO-level thinking without a $150K salary.'
  },
  {
    kicker: 'For Brokers',
    title: "You're closing deals, not managing marketing.",
    body: "Listings aren't getting attention. Social is a ghost town. You can't compete with larger brokerages — and prospecting is manual, with no automation or consistency.",
    need: 'You need content and lead automation so you can focus on sales.'
  },
  {
    kicker: 'For Marina Ops',
    title: 'Seasonal chaos is killing your margins.',
    body: "You need occupancy, but marketing takes bandwidth you don't have. Members disengage off-season. Competing platforms own your search results.",
    need: 'You need marketing on autopilot so you can manage operations.'
  }
];

const steps = [
  ['Strategy Audit', 'We audit your brand, competitive position and marketing gaps. Where are you leaving money on the table?', '2 Weeks'],
  ['Roadmap & Framework', 'Quarterly focus, messaging hierarchy, content pillars, channel strategy — your 90-day battle plan.', 'Quarterly Refresh'],
  ['Build & Automate', 'Using LLMs and AI tools we execute and automate. Most production runs on autopilot.', 'Ongoing Optimization'],
  ['Measure & Scale', 'Monthly performance reports, lead pipeline tracking, content ROI analysis. What gets measured gets improved.', 'Monthly Reporting']
];

const services = [
  ['Fractional CMO', 'Strategic leadership, marketing roadmaps, launch planning, positioning and competitive analysis.', ['Quarterly strategy sessions', 'Marketing roadmaps', 'Launch frameworks', 'Brand consistency audits']],
  ['Content Automation', 'AI-powered content production at 3× the speed of traditional teams.', ['Spec sheets → case studies', 'Listings → social posts', 'Blog research → articles', 'Auto-generated newsletters']],
  ['Lead Generation', 'Conversions on autopilot with behavioral automation and nurture systems.', ['Qualification workflows', 'Behavioral email sequences', 'Social engagement automation', 'Seasonal campaign triggers']],
  ['Performance Tracking', 'Metrics that matter. Monthly reports built for stakeholders, not vanity dashboards.', ['Monthly performance reports', 'Lead pipeline tracking', 'Content ROI analysis', 'Competitive benchmarking']]
];

const faqs = [
  ["What's included in RB Yacht Marketing's Fractional CMO services?", 'Strategic marketing leadership, documented deliverables, AI-enhanced execution support and ongoing accountability — tailored to the growth stage and goals of your marine business. Every engagement produces tangible assets you keep.'],
  ['How long does it take to see results?', 'Most clients see early signals — sharper messaging, faster content output and a filling pipeline — within the first 30–60 days, with compounding results across the first quarter.'],
  ['What does the Fractional CMO service cost?', 'Engagements are month-to-month and scoped to your goals. Pricing is by inquiry across three tiers — Foundation, Partner and Full Partner.'],
  ['How does the Fractional CMO service work day-to-day?', 'You get a senior marketing leader embedded in your business — strategy calls on a regular cadence, hands-on execution between sessions and AI automations running in the background.'],
  ['Can this work alongside my existing marketing team or agency?', 'Absolutely. We frequently provide the senior strategy and AI tooling that lets your existing team or agency execute faster and with more focus.'],
  ["What's the difference between a Fractional CMO and hiring a marine marketing agency?", 'An agency executes campaigns; a Fractional CMO owns the strategy, accountability and growth direction — then orchestrates execution to deliver it.'],
  ['How quickly can we get started?', 'Most engagements kick off within one to two weeks of your audit, starting with a strategy sprint and the first automation workflows.'],
  ['What marine industry segments do you work with?', 'Boat builders, yacht and charter brokers, marina operators and marine service brands — anyone marketing at the premium end of the water.'],
  ['What happens when the engagement ends?', 'You keep every asset we build — strategy docs, frameworks, automations and dashboards — so the value compounds long after the engagement.'],
  ['How do I know if this is right for my marine business?', "Book a free 40-minute audit. If a Fractional CMO isn't the right fit, we'll tell you — and point you toward what is."]
];

const plans = [
  { kicker: 'Starter', name: 'Foundation', description: 'For teams with execution capability who need senior strategic direction.', items: ['Quarterly strategy sessions', 'Marketing roadmap & quarterly focus', 'Monthly performance report', 'AI automation setup (1 workflow)', 'Email: priority access'] },
  { featured: true, name: 'Partner', description: 'Embedded leadership plus AI-powered automation across content and lead gen.', items: ['Everything in Foundation', 'Content automation (3 workflows)', 'Lead nurture sequences', 'Social media automation', 'AI Advisor Bot setup', 'Bi-weekly strategy calls'] },
  { kicker: 'Scale', name: 'Full Partner', description: 'Full marketing department, activated overnight. Built for events and rapid scale.', items: ['Everything in Partner', 'Full content pipeline automation', 'Team leadership & training', 'Events & boat show strategy', 'Custom AI development', 'Weekly calls + on-call access'] }
];

const testimonials = [
  { quote: 'Romina played an instrumental role in shaping how our company presents itself to the international market. From the outset, she brought a rare combination of strategic intelligence, creative flair, and disciplined execution.', initials: 'JE', name: 'Jim Evans', role: 'Managing Partner, SuperYachtsMonaco' },
  { quote: 'Working with Romina has been one of the most enriching experiences of my career. Her wealth of knowledge and contacts among the international yachting industry gave us tranquility and confidence.', initials: 'IA', name: 'Ione Astondoa', role: 'Owner, Astondoa Yachts' },
  { quote: "Romina singlehandedly put G Marine on the industry map, converting us from a small family-owned business to a boat dealership with worldwide recognition.", initials: 'AG', name: 'Alberto Galante', role: 'President/CEO, G Marine Yacht Sales' },
  { quote: 'She took my goals and vision and made them a reality. I received very positive feedback on our new website from clients and gained many businesses with our new online identity.', initials: 'JM', name: 'Javier Maldonado', role: 'Operations Director, YachtGala Galapagos' }
];



const BRAND_LOGOS = [
  ['32-Americas-Cup-regatta.png', "America's Cup Regatta"],
  ['admiral-yachts.png', 'Admiral Yachts'],
  ['Astondoa-Yachts.png', 'Astondoa Yachts'],
  ['Axopar-boats.png', 'Axopar Boats'],
  ['CLYachts_Logo.png', 'CL Yachts'],
  ['evo-yachts-copy.png', 'Evo Yachts'],
  ['fairline-yachts.png', 'Fairline Yachts'],
  ['florida-yachts-international.png', 'Florida Yachts International'],
  ['g-marine-yacht-sales-.png', 'G Marine Yacht Sales'],
  ['IYB-Yachts.png', 'IYB Yachts'],
  ['Marina-Real-Juan-Carlos-I.png', 'Marina Real Juan Carlos I'],
  ['prj-boats.png', 'PRJ Boats'],
  ['Revolution-yacht-Group.png', 'Revolution Yacht Group'],
  ['Schaefer-yachts.png', 'Schaefer Yachts'],
  ['sundeck-yachts.png', 'Sundeck Yachts'],
  ['Tecnomar.png', 'Tecnomar'],
  ['TP-52-regatta.png', 'TP52 Regatta'],
  ['victory-yachts.png', 'Victory Yachts'],
  ['Wally-yachts.png', 'Wally Yachts'],
  ['yacht-gala.png', 'Yacht Gala']
];

function BrandRail() {
  return <section className="brand-rail" aria-labelledby="brand-rail-title">
    <h2 className="brand-rail__title" id="brand-rail-title">Trusted by</h2>
    <div className="brand-rail__viewport">
      <div className="brand-rail__track brand-rail__track--marquee">
        {[...BRAND_LOGOS, ...BRAND_LOGOS].map(([file, name], index) => <div className="brand-logo" aria-hidden={index >= BRAND_LOGOS.length} key={file + '-' + index}>
          <img src={'/assets/brands/' + file} alt={index < BRAND_LOGOS.length ? name : ''} loading="lazy" />
        </div>)}
      </div>
    </div>
  </section>;
}

function ScrollRevealManager() {
  useEffect(() => {
    const revealItems = [];
    const register = (element, direction, delay = 0) => {
      if (!element || element.dataset.scrollReveal) return;
      element.dataset.scrollReveal = direction;
      element.style.setProperty('--reveal-delay', delay + 'ms');
      revealItems.push(element);
    };

    document.querySelectorAll('main .h2, main .final h2').forEach((title) => register(title, 'left'));
    const contentSelectors = [
      '#solution .solution__intro', '#solution .steps', '#solution .section-action',
      '#about .about__media', '#about .about__body', '#about .about__quote', '#about .about__note',
      '#cases .case', '#faq .faq__list', '.testi__slider', '.testi__dots',
      '.final__body', '.final__cta', '.final__link', '.news__form', '.news__success'
    ];
    contentSelectors.forEach((selector, index) => register(document.querySelector(selector), 'right', Math.min((index % 3) * 70, 140)));
    ['#problem .pcard', '#services .svc', '#pricing .plan'].forEach((selector) => {
      document.querySelectorAll(selector).forEach((card, index) => register(card, 'up', index * 105));
    });

    if (!('IntersectionObserver' in window) || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      revealItems.forEach((item) => item.classList.add('is-visible'));
      return undefined;
    }

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        entry.target.classList.add('is-visible');
        observer.unobserve(entry.target);
      });
    }, { rootMargin: '0px 0px -12% 0px', threshold: 0.12 });
    revealItems.forEach((item) => observer.observe(item));
    return () => observer.disconnect();
  }, []);
  return null;
}

function HeroNetwork() {
  // Node corridor traces the lead yacht's wake: it narrows to the fleet's
  // convergence point on the horizon (~560,250) and widens toward the stern
  // and off-screen bottom-right, matching the boats' direction of travel.
  const nodes = [
    [621,215],[790,285],[964,365],[1151,455],[1349,550],[1559,655],[1745,750],
    [574,250],[725,325],[889,410],[1069,505],[1261,610],[1471,725],[1681,845],
    [533,285],[667,365],[819,460],[982,565],[1157,680],[1337,800],[1506,885],
    [475,330],[597,425],[731,530],[877,640],[1034,755],[1197,865],
    [685,240],[860,330],[1040,430],[1227,530],[1425,640],[1634,760],
    [778,395],[935,495],[1098,600],[1273,715],
    [621,470],[760,580],[912,690],[1075,800],
    [557,395],[691,505],[842,615],[999,730]
  ];
  const links = [];
  nodes.forEach(([x1, y1], from) => nodes.slice(from + 1).forEach(([x2, y2], offset) => {
    const distance = Math.hypot(x2 - x1, y2 - y1);
    if (distance > 72 && distance < 220) links.push([from, from + offset + 1]);
  }));
  // Every route flows stern → horizon (bottom-right → top-left): the signals
  // stream away behind the lead yacht like her wake, dissipating at the horizon.
  const routes = [
    'M1745 750 L1559 655 L1349 550 L1151 455 L964 365 L790 285 L621 215',
    'M1681 845 L1471 725 L1261 610 L1069 505 L889 410 L725 325 L574 250',
    'M1506 885 L1337 800 L1157 680 L982 565 L819 460 L667 365 L533 285',
    'M1197 865 L1034 755 L877 640 L731 530 L597 425 L475 330',
    'M1634 760 L1425 640 L1227 530 L1040 430 L860 330 L685 240',
    'M1681 845 L1471 725 L1273 715 L1098 600 L889 410 L725 325 L621 215',
    'M1506 885 L1273 715 L1098 600 L935 495 L778 395 L574 250',
    'M1197 865 L999 730 L842 615 L691 505 L533 285',
    'M1745 750 L1559 655 L1425 640 L1227 530 L1040 430 L889 410 L685 240',
    'M1197 865 L1075 800 L912 690 L760 580 L557 395',
    'M1337 800 L1157 680 L935 495 L778 395 L621 470 L475 330',
    'M1634 760 L1425 640 L1261 610 L1069 505 L860 330 L621 215'
  ];
  return <div className="hero-network" aria-hidden="true"><svg viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice"><defs><filter id="signalGlow" x="-300%" y="-300%" width="700%" height="700%"><feGaussianBlur stdDeviation="3.5" result="blur" /><feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge></filter></defs><g className="hero-network__links">{links.map(([from, to], index) => <line x1={nodes[from][0]} y1={nodes[from][1]} x2={nodes[to][0]} y2={nodes[to][1]} key={index} />)}</g><g filter="url(#signalGlow)">{routes.flatMap((path, index) => {
      const dur = 7.5 + (index % 5) * .9;
      // Two phase-shifted dots per route at constant linear speed; opacity is
      // synced to the motion so each dot fades out before its loop restarts.
      return [0, 1].map((phase) => {
        const begin = (-index * .73 - phase * dur / 2) + 's';
        return <circle className="hero-network__signal" r={index % 3 === 0 ? 4.2 : 3.2} opacity="0" key={path + '-' + phase}>
          <animateMotion path={path} dur={dur + 's'} begin={begin} repeatCount="indefinite" />
          <animate attributeName="opacity" values="0;1;1;0" keyTimes="0;0.1;0.82;1" dur={dur + 's'} begin={begin} repeatCount="indefinite" />
        </circle>;
      });
    })}</g></svg><div className="hero-network__wash" /></div>;
}

function App() {
  const [menuOpen, setMenuOpen] = useState(false);
  const [modal, setModal] = useState(null);
  const [faqOpen, setFaqOpen] = useState(0);
  const [testimonial, setTestimonial] = useState(0);
  const [newsletterDone, setNewsletterDone] = useState(false);

  useEffect(() => {
    const timer = window.setInterval(() => setTestimonial((value) => (value + 1) % testimonials.length), 6000);
    return () => window.clearInterval(timer);
  }, []);

  useEffect(() => {
    document.body.style.overflow = modal ? 'hidden' : '';
    const close = (event) => event.key === 'Escape' && setModal(null);
    document.addEventListener('keydown', close);
    return () => {
      document.body.style.overflow = '';
      document.removeEventListener('keydown', close);
    };
  }, [modal]);

  return <>
    <header className="hero" id="top">
      <div className="hero__media" data-original-hero={ORIGINAL_HERO_ASSET}><img src={HERO_MODE === 'original' ? ORIGINAL_HERO_ASSET : CLEAN_HERO_ASSET} alt="Motor yacht cruising near Monaco at blue hour" />{HERO_MODE === 'clean-network' && <HeroNetwork />}</div>
      <div className="hero__scrim" />
      <nav className="nav" aria-label="Main navigation">
        <div className="wrap nav__inner">
          <a className="logo logo--light" href="#top" aria-label="RB Yacht Marketing home"><img className="logo__mark" src="/favicon.png" alt="" /><span className="logo__word"><span className="light">Yacht Marketing</span></span></a>
          <button className="nav__toggle" type="button" aria-expanded={menuOpen} aria-controls="main-menu" onClick={() => setMenuOpen(!menuOpen)}>{menuOpen ? 'Close' : 'Menu'}</button>
          <div className={`nav__links ${menuOpen ? 'is-open' : ''}`} id="main-menu" onClick={() => setMenuOpen(false)}>
            <a href="#top">Home</a><a href="#services">Services</a><a href="#solution">Fractional CMO</a><a href="#cases">Case Studies</a><a href="#about">About</a><a href="#contact">Contact</a>
          </div>
          <button className="btn btn--pink btn--sm nav__cta" type="button" onClick={() => setModal('schedule')}>Schedule a call</button>
        </div>
      </nav>
      <div className="wrap hero__inner"><div className="hero__col">
        <h1>Leave The Competition <span className="accent">In Your Wake.</span></h1>
        <p className="hero__sub">Strategic digital marketing leadership and AI-powered automation for boat builders, brokers and marina operators who want to grow without the overhead.</p>
        <div className="hero__cta"><button className="btn btn--pink" onClick={() => setModal('playbook')}>Get your CMO Playbook</button></div>
      </div></div>
      <div className="statbar"><div className="wrap statbar__grid">
        {[['20+', 'Years Yacht Marketing Expertise'], ['3×', 'Faster Content Output'], ['15+', 'Marine Brands Served'], ['∞', 'AI-Powered Scalability']].map(([value, label]) => <div className="stat" key={label}><div className="stat__num">{value}</div><div className="stat__label">{label}</div></div>)}
      </div></div>
    </header>

    <ScrollRevealManager />

    <main>
      <section className="section" id="problem"><div className="wrap">
        <SectionHead eyebrow="The Problem" title={<>Your Marine Marketing <span className="accent">Is Stuck.</span></>} />
        <div className="problem__grid">{problems.map((item) => <article className="pcard" key={item.kicker}><div className="pcard__kicker">{item.kicker}</div><h3>{item.title}</h3><p className="pcard__body">{item.body}</p><div className="pcard__rule" /><div className="pcard__need"><span className="arr">→</span><span>{item.need}</span></div></article>)}</div>
      </div></section>

      <section className="solution" id="solution"><div className="wrap solution__inner">
        <h2 className="h2">Strategy Without <span className="accent">the Overhead.</span></h2>
        <div className="solution__intro"><p>The best marketing leaders don't build empires. They deliver results.</p><p>RBYM's Fractional CMO model gives you senior-level strategy, hands-on execution, and AI-powered automation, without the cost or complexity of a full in-house team. Think of it as a complete marketing department, scaled on demand.</p></div>
        <div className="steps">{steps.map(([title, body, tag], index) => <div className="step" key={title}><div className="step__top"><span className="step__num">{String(index + 1).padStart(2, '0')}</span><span className="step__arrow">→</span></div><h3>{title}</h3><p className="step__body">{body}</p><span className="tag">{tag}</span></div>)}</div>
        <div className="section-action"><button className="btn btn--pink" type="button" onClick={() => setModal('schedule')}>Book a free consultation</button></div>
      </div></section>

      <section className="section section--grey" id="services"><div className="wrap">
        <SectionHead eyebrow="Services" title={<>Built for Marine. <span className="accent">Powered by AI.</span></>} lead="Every service is designed for the marine industry — not adapted from generic marketing playbooks." />
        <div className="svc__grid">{services.map(([title, body, items], index) => <article className="svc" key={title}><span className="svc__num">{String(index + 1).padStart(2, '0')}</span><h3>{title}</h3><p className="svc__body">{body}</p><div className="svc__rule" /><DiamondList items={items} /></article>)}</div>
      </div></section>

      <section className="section" id="about"><div className="wrap about__grid">
        <div className="about__media"><a href="https://www.linkedin.com/in/rominabompani/" target="_blank" rel="noreferrer"><img src="/assets/romina.webp" alt="Romina Bompani" /></a><div className="about__badge"><div className="n">20<sup>+</sup></div><div className="l">Years in Yacht Marketing</div></div></div>
        <div className="about__text"><h2 className="h2">Where Yacht Marketing Expertise Meets <span className="accent">the Age of AI.</span></h2><p className="about__body">I've spent 20+ years inside yacht marketing — launching models, managing broker networks across key markets, and building brands that command premium positioning in a fiercely competitive sector.</p><blockquote className="about__quote">“I'm not your consultant. I'm not your agency. I'm your CMO — without the overhead.”</blockquote><p className="about__note">Deep industry credibility & network + AI tooling + fractional pricing that actually works.</p></div>
      </div></section>

      <section className="section section--grey" id="cases"><div className="wrap">
        <SectionHead eyebrow="Case Studies" title={<>How Marine Companies Grow With <span className="accent">Fractional CMO + AI.</span></>} />
        <article className="case"><div className="case__media"><img src="/assets/monaco-rendering.webp" alt="Superyacht in Monaco" /><span className="case__badge">Featured</span></div><div className="case__body"><h3>The Boutique Broker Who Beat Big Brokerages.</h3><p>How one broker increased revenue and closed more deals using modern tools and lead nurture workflows.</p><div className="case__stats">{[['5%', 'Revenue'], ['+50%', 'CA Sales Leads'], ['+15%', 'CA Charter Leads']].map(([value, label]) => <div className="case__stat" key={label}><div className="v">{value}</div><div className="k">{label}</div></div>)}</div><div className="case__cta"><a className="btn btn--pink" href="/case-study" target="_blank" rel="noreferrer">Read case study</a></div></div></article>
      </div></section>

      <section className="section" id="faq"><div className="wrap faq__grid"><div className="faq__head"><h2 className="h2">Questions, <span className="accent">Answered.</span></h2><p className="lead">Common questions about Fractional CMO services, pricing and how engagements work.</p></div><div className="faq__list">{faqs.map(([question, answer], index) => { const open = faqOpen === index; return <div className={`faq__item ${open ? 'open' : ''}`} key={question}><button className="faq__q" aria-expanded={open} onClick={() => setFaqOpen(open ? -1 : index)}><span className="faq__n">{String(index + 1).padStart(2, '0')}</span><span className="faq__qt">{question}</span><span className="faq__icon">{open ? '×' : '+'}</span></button><div className="faq__a" aria-hidden={!open}><div>{answer}</div></div></div>; })}</div></div></section>

      <section className="section section--grey" id="pricing"><div className="wrap"><SectionHead eyebrow="Pricing" title={<>Fractional CMO <span className="accent">Pricing.</span></>} lead="Flexible, scalable and transparent. All packages include AI-powered automation setup and management." /><div className="price__grid">{plans.map((plan) => <article className={`plan ${plan.featured ? 'plan--featured' : ''}`} key={plan.name}>{plan.featured ? <span className="plan__pop">Most Popular</span> : <div className="plan__kicker">{plan.kicker}</div>}<h3>{plan.name}</h3><p className="plan__desc">{plan.description}</p><div className="plan__rule" /><div className="plan__inq">By Inquiry</div><div className="plan__sub">Month-to-month engagements</div><DiamondList items={plan.items} /><button className={`btn ${plan.featured ? 'btn--pink' : 'btn--outline-dark'}`} onClick={() => setModal('inquiry')}>Inquire now</button></article>)}</div></div></section>

      <section className="section section--grey testi"><div className="wrap"><h2 className="h2">What Marine Leaders <span className="accent">Say.</span></h2><div className="testi__slider" aria-live="polite">{testimonials.map((item, index) => <div className={`testi__slide ${testimonial === index ? 'active' : ''}`} key={item.name}><div className="testi__quote"><span className="testi__mark">“</span><p>{item.quote}</p><div className="testi__person"><span className="testi__av">{item.initials}</span><div><div className="testi__name">{item.name}</div><div className="testi__role">{item.role}</div></div></div></div></div>)}</div><div className="testi__dots">{testimonials.map((item, index) => <button className={testimonial === index ? 'on' : ''} key={item.name} onClick={() => setTestimonial(index)} aria-label={`Show testimonial ${index + 1}`} />)}</div></div></section>

      <section className="final" id="contact"><div className="final__media"><img src="/assets/hero-yacht.png" alt="" /></div><div className="final__scrim" /><div className="wrap final__inner"><h2>Let's Audit Your <span className="accent">Marketing.</span></h2><p className="final__body">Book a free 40-minute CMO audit. We'll look at your current strategy, competitive position and biggest opportunities. No pitch. No pressure. Just honest feedback and a clear starting point.</p><div className="final__cta"><button className="btn btn--pink" type="button" onClick={() => setModal('audit')}>Schedule your free audit</button></div><button className="final__link" onClick={() => setModal('playbook')}>Or download the Fractional CMO Playbook →</button></div></section>

      <section className="section section--grey"><div className="wrap news__grid"><div><h2 className="h2">Monthly AI + Marine Marketing Tips.</h2><p className="news__sub">Actionable insights, tool recommendations and automation shortcuts. First Wednesday of each month.</p></div>{newsletterDone ? <div className="news__success" role="status">You're on the list. Check your inbox for the next issue.</div> : <form className="news__form" onSubmit={(event) => { event.preventDefault(); setNewsletterDone(true); }}><div className="news__field"><input type="email" name="email" required placeholder="your@email.com" aria-label="Email address" /><span className="ic">✉</span></div><button className="btn btn--pink" type="submit">Subscribe →</button></form>}</div></section>
    </main>

    <BrandRail />
    <Footer openPlaybook={() => setModal('playbook')} openSchedule={() => setModal('schedule')} openInquiry={() => setModal('inquiry')} />
    {modal && <QualificationModal intent={modal} onClose={() => setModal(null)} />}
  </>;
}

function SectionHead({ eyebrow, title, lead }) {
  return <div className="section__head"><h2 className="h2">{title}</h2>{lead && <p className="lead">{lead}</p>}</div>;
}

function DiamondList({ items }) {
  return <ul className="diamonds">{items.map((item) => <li key={item}>{item}</li>)}</ul>;
}


const COUNTRIES = ['Australia', 'Austria', 'Belgium', 'Brazil', 'Canada', 'Croatia', 'Cyprus', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Hong Kong', 'Italy', 'Malta', 'Monaco', 'Montenegro', 'Netherlands', 'New Zealand', 'Norway', 'Portugal', 'Singapore', 'South Africa', 'Spain', 'Sweden', 'Switzerland', 'Turkey', 'United Arab Emirates', 'United Kingdom', 'United States', 'Other'];
const PHONE_CODES = [['+1', 'US / Canada'], ['+33', 'France / Monaco'], ['+34', 'Spain'], ['+39', 'Italy'], ['+44', 'United Kingdom'], ['+30', 'Greece'], ['+356', 'Malta'], ['+385', 'Croatia'], ['+382', 'Montenegro'], ['+351', 'Portugal'], ['+31', 'Netherlands'], ['+32', 'Belgium'], ['+41', 'Switzerland'], ['+49', 'Germany'], ['+971', 'UAE'], ['+65', 'Singapore'], ['+852', 'Hong Kong'], ['+61', 'Australia'], ['+64', 'New Zealand'], ['+27', 'South Africa'], ['+90', 'Turkey'], ['+55', 'Brazil']];
const MARKETING_INITIATIVES = ['Marketing strategy', 'Lead generation', 'Content and social', 'CRM and nurture', 'Brand or launch positioning', 'Performance reporting'];
const AI_INITIATIVES = ['Content automation', 'Lead qualification', 'Workflow automation', 'CRM intelligence', 'Reporting and insights', 'Exploring opportunities'];

function QualificationModal({ intent, onClose }) {
  const [step, setStep] = useState(1);
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState('');
  const [developmentMode, setDevelopmentMode] = useState(false);
  const [form, setForm] = useState({ name: '', email: '', linkedIn: '', country: '', phoneCountryCode: '+1', phone: '', whatsappConsent: false, company: '', role: '', employeeCount: '', marketingInitiatives: [], aiInitiatives: [], message: '', gdprConsent: false, websiteCheck: '' });
  const headingRef = useRef(null);
  const flow = {
    playbook: { title: 'Get Your CMO Playbook.', description: 'Complete the qualification steps to open the Playbook.', button: 'Access the Playbook →', outcome: 'playbook', successTitle: 'Your Playbook is opening.', successDescription: 'If the Playbook did not open, check that your browser allows pop-ups.' },
    schedule: { title: 'Schedule a Call.', description: 'Complete the qualification steps, then choose a meeting time with your details already filled in.', button: 'Continue to scheduling →', outcome: 'calendar', successTitle: 'Opening the calendar.', successDescription: 'Choose the time that works best for you.' },
    audit: { title: 'Schedule Your Free Audit.', description: 'Complete the qualification steps, then choose your audit time with your details already filled in.', button: 'Continue to scheduling →', outcome: 'calendar', successTitle: 'Opening the calendar.', successDescription: 'Choose the time that works best for you.' },
    inquiry: { title: 'Start an Enquiry.', description: 'Tell us about your business and leave a message for Romina.', button: 'Send enquiry →', outcome: 'message', successTitle: 'Your enquiry has been received.', successDescription: 'Thank you. Romina will respond using the contact details you provided.' }
  }[intent] || null;

  useEffect(() => headingRef.current?.focus(), [step]);

  function update(event) {
    const { name, value, type, checked } = event.target;
    setForm((current) => ({ ...current, [name]: type === 'checkbox' ? checked : value }));
  }

  function toggleList(name, value) {
    setForm((current) => ({ ...current, [name]: current[name].includes(value) ? current[name].filter((item) => item !== value) : [...current[name], value] }));
  }

  async function submit(event) {
    event.preventDefault();
    setError('');
    if (!event.currentTarget.reportValidity()) return;
    if (step < 3) { setStep((value) => value + 1); return; }
    if (!form.marketingInitiatives.length || !form.aiInitiatives.length) {
      setError('Choose at least one marketing initiative and one AI initiative.');
      return;
    }
    setStatus('sending');
    try {
      const response = await fetch('/api/qualified-lead', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ ...form, intent }) });
      const result = await response.json();
      if (!response.ok) throw new Error(result.error || 'Unable to process your request.');
      setDevelopmentMode(Boolean(result.developmentMode));
      setStatus('success');
      // Persist name + email so gated resources (e.g. /playbook) can prefill Calendly.
      try { localStorage.setItem('rbym-lead', JSON.stringify({ name: form.name, email: form.email })); } catch (storageError) { /* private mode */ }
      if (flow.outcome === 'playbook') window.open(PLAYBOOK, '_blank', 'noopener');
      if (flow.outcome === 'calendar') {
        const booking = new URL(result.calendlyUrl || CALENDLY);
        booking.searchParams.set('name', form.name);
        booking.searchParams.set('email', form.email);
        window.location.assign(booking.toString());
      }
    } catch (requestError) {
      setStatus('error');
      setError(requestError.message || 'Something went wrong. Please try again.');
    }
  }

  const titles = ['Contact Info', 'Business Info', 'Marketing + AI Initiatives'];
  return <div className="pbm is-open" role="presentation"><button className="pbm__backdrop" aria-label="Close dialog" onClick={onClose} /><div className="pbm__dialog pbm__dialog--qualification" role="dialog" aria-modal="true" aria-labelledby="qualification-modal-title"><button className="pbm__x" type="button" aria-label="Close" onClick={onClose}>×</button>{status === 'success' ? <div className="pbm__body pbm__success"><div className="pbm__check">✓</div><h3 className="pbm__title">{flow.successTitle}</h3><p className="pbm__sub">{developmentMode ? 'Local preview complete. Add Mailjet credentials before launch to deliver lead notifications.' : flow.successDescription}</p><button className="btn btn--outline-dark" onClick={onClose}>Close</button></div> : <div className="pbm__body"><div className="pbm__stepper" aria-label="Qualification request progress">{titles.map((title, index) => <div className={'pbm__step ' + (step === index + 1 ? 'is-current' : '') + (step > index + 1 ? ' is-complete' : '')} key={title}><span>{step > index + 1 ? '✓' : index + 1}</span><small>{title}</small></div>)}</div><h3 ref={headingRef} tabIndex="-1" id="qualification-modal-title" className="pbm__title">{step === 1 ? flow.title : titles[step - 1]}</h3><p className="pbm__sub">Step {step} of 3 · {flow.description}</p><form className="pbm__form pbm__qualification" onSubmit={submit}>{step === 1 && <div className="pbm__panel"><div className="pbm__field-grid"><label className="pbm__field"><span className="pbm__label">Full name</span><input name="name" value={form.name} onChange={update} autoComplete="name" required /></label><label className="pbm__field"><span className="pbm__label">Work email</span><input type="email" name="email" value={form.email} onChange={update} autoComplete="email" required /></label></div><label className="pbm__field"><span className="pbm__label">LinkedIn profile <small>(optional)</small></span><input type="text" name="linkedIn" value={form.linkedIn} onChange={update} placeholder="linkedin.com/in/your-profile" /></label><label className="pbm__field"><span className="pbm__label">Country</span><select name="country" value={form.country} onChange={update} required><option value="">Select country</option>{COUNTRIES.map((country) => <option key={country}>{country}</option>)}</select></label><label className="pbm__field"><span className="pbm__label">Mobile number <small>(optional)</small></span><span className="pbm__phone"><select name="phoneCountryCode" value={form.phoneCountryCode} onChange={update} aria-label="Phone country code">{PHONE_CODES.map(([code, country]) => <option value={code} key={code + country}>{code} · {country}</option>)}</select><input type="tel" name="phone" value={form.phone} onChange={update} autoComplete="tel-national" placeholder="Mobile number" required={form.whatsappConsent} /></span></label><label className="pbm__consent"><input type="checkbox" name="whatsappConsent" checked={form.whatsappConsent} onChange={update} /><span>I wish to be contacted via WhatsApp.</span></label></div>}{step === 2 && <div className="pbm__panel"><label className="pbm__field"><span className="pbm__label">Company</span><input name="company" value={form.company} onChange={update} autoComplete="organization" required /></label><div className="pbm__field-grid"><label className="pbm__field"><span className="pbm__label">Your role</span><input name="role" value={form.role} onChange={update} autoComplete="organization-title" /></label><label className="pbm__field"><span className="pbm__label">Employee count</span><select name="employeeCount" value={form.employeeCount} onChange={update} required><option value="">Select range</option>{['1–5', '6–20', '21–50', '51–100', '101–250', '251–500', '500+'].map((range) => <option key={range}>{range}</option>)}</select></label></div></div>}{step === 3 && <div className="pbm__panel"><ToggleGroup title="Marketing initiatives" name="marketingInitiatives" options={MARKETING_INITIATIVES} selected={form.marketingInitiatives} toggle={toggleList} /><ToggleGroup title="AI initiatives" name="aiInitiatives" options={AI_INITIATIVES} selected={form.aiInitiatives} toggle={toggleList} />{flow.outcome === 'message' && <label className="pbm__field"><span className="pbm__label">Your message</span><textarea name="message" value={form.message} onChange={update} rows="4" placeholder="How can we help?" required /></label>}<label className="pbm__consent pbm__consent--gdpr"><input type="checkbox" name="gdprConsent" checked={form.gdprConsent} onChange={update} required /><span>I authorise RB Yacht Marketing to process this information to respond to my request, in accordance with GDPR.</span></label><label className="pbm__honeypot" aria-hidden="true">Website<input name="websiteCheck" value={form.websiteCheck} onChange={update} tabIndex="-1" autoComplete="off" /></label></div>}{error && <p className="pbm__error" role="alert">{error}</p>}<div className="pbm__actions">{step > 1 && <button className="btn btn--outline-dark" type="button" onClick={() => { setError(''); setStep((value) => value - 1); }}>Back</button>}<button className="btn btn--pink" type="submit" disabled={status === 'sending'}>{status === 'sending' ? 'Sending…' : step < 3 ? 'Continue →' : flow.button}</button></div></form></div>}</div></div>;
}

function ToggleGroup({ title, name, options, selected, toggle }) {
  return <fieldset className="pbm__choices"><legend>{title}</legend><div>{options.map((option) => <label className={selected.includes(option) ? 'is-selected' : ''} key={option}><input type="checkbox" name={name} value={option} checked={selected.includes(option)} onChange={() => toggle(name, option)} /><span>{option}</span></label>)}</div></fieldset>;
}

function ContactReveal() {
  const [stage, setStage] = useState('idle');
  const [challenge, setChallenge] = useState(null);
  const [answer, setAnswer] = useState('');
  const [contact, setContact] = useState(null);
  const [error, setError] = useState('');

  async function begin() {
    setError('');
    try {
      const response = await fetch('/api/contact-challenge');
      setChallenge(await response.json());
      setAnswer('');
      setStage('challenge');
    } catch (requestError) {
      setError('Unable to load the check. Please try again.');
    }
  }

  async function submit(event) {
    event.preventDefault();
    setError('');
    try {
      const response = await fetch('/api/contact-reveal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: challenge.token, answer }) });
      const result = await response.json();
      if (!response.ok) {
        if (response.status === 410) await begin();
        throw new Error(result.error || 'Please try again.');
      }
      setContact(result);
      setStage('revealed');
    } catch (requestError) {
      setError(requestError.message);
    }
  }

  if (stage === 'revealed' && contact) return <div className="footer__reveal"><a href={'mailto:' + contact.email}>{contact.email}</a>{contact.phones.map((phone) => <a key={phone} href={'tel:' + phone.replace(/[^+\d]/g, '')}>{phone}</a>)}</div>;
  if (stage === 'challenge' && challenge) return <form className="footer__reveal-form" onSubmit={submit}><label><span>{challenge.question}</span><input value={answer} onChange={(event) => setAnswer(event.target.value)} inputMode="numeric" autoFocus aria-label="Answer" required /></label><button className="btn btn--pink btn--sm" type="submit">Show</button>{error && <p className="footer__reveal-error" role="alert">{error}</p>}</form>;
  return <><button className="footer__contact-link" type="button" onClick={begin}>Show email &amp; phone</button>{error && <p className="footer__reveal-error" role="alert">{error}</p>}</>;
}

function Footer({ openPlaybook, openSchedule, openInquiry }) {
  return <footer className="footer"><div className="wrap"><div className="footer__top"><div className="footer__brand"><a className="logo logo--light" href="#top"><img className="logo__mark" src="/favicon.png" alt="" /><span className="logo__word"><span className="light">Yacht Marketing</span></span></a><p className="footer__desc">The Fractional CMO and AI Advisor for the marine industry. Based between Fort Lauderdale & Monaco, serving clients globally.</p><button className="btn btn--pink btn--sm" type="button" onClick={openSchedule}>Book a call</button><div className="footer__connect"><h4>Contact</h4><button className="footer__contact-link" type="button" onClick={openInquiry}>Send an enquiry</button><ContactReveal /><a href="https://www.linkedin.com/in/rominabompani/" target="_blank" rel="noreferrer">LinkedIn</a></div></div><div className="footer__col"><h4>Company</h4><a href="#about">About Romina</a><a href="#solution">How It Works</a><a href="#cases">Case Studies</a><button onClick={openInquiry}>Contact</button></div><div className="footer__col"><h4>Services</h4><a href="#services">Fractional CMO</a><a href="#services">Content Automation</a><a href="#services">Lead Automation</a></div><div className="footer__col"><h4>Resources</h4><a href="/portfolio">Portfolio</a><button onClick={openPlaybook}>CMO Playbook</button><a href="#faq">FAQ</a><a href="/privacy">Privacy &amp; Cookies</a><button onClick={() => window.rbymConsent && window.rbymConsent.open()}>Cookie settings</button></div></div><div className="footer__bar"><span>© 2026 RB Yacht Marketing. All rights reserved.</span><span>Fort Lauderdale — Monaco · Global Reach · Powered by <a className="footer__credit" href="https://yachtingstack.ai/" target="_blank" rel="noreferrer">YachtingStack</a></span></div></div></footer>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
