// ───────── Sections: Problem, Solution, Services, Systems, Case, Founder, Process, Why, Final CTA, Footer ─────────

// ── Problem ──
const Problem = () => {
  const cards = [
    { icon: "clock", title: "Slow Operations", body: "Manual tasks, repetitive admin, and disconnected tools slow down the business and create unnecessary workload." },
    { icon: "miss", title: "Missed Revenue Opportunities", body: "Slow follow-up, weak systems, and inconsistent marketing cause leads and customers to slip away." },
    { icon: "disconnect", title: "Disconnected Marketing Systems", body: "Ads, email, SEO, content, CRM, and reporting often operate separately instead of working as one growth engine." },
  ];
  return (
    <section className="section" id="problem">
      <div className="container">
        <div className="section-head reveal">
          <div className="eyebrow">The Problem</div>
          <h2 className="h-section">Manual Work Is Becoming Your Most Expensive Bottleneck.</h2>
          <p className="lead">
            Most businesses are still running on disconnected tools, manual follow-ups, slow reporting,
            inconsistent marketing, and underused data. That creates friction everywhere: time gets wasted,
            opportunities get missed, and growth becomes harder than it needs to be.
          </p>
        </div>
        <div className="grid-3">
          {cards.map((c, i) => (
            <div className="glass glass-card reveal" key={i} style={{ transitionDelay: `${i * 80}ms` }}>
              <div className="icon-wrap"><Icon name={c.icon} /></div>
              <h3 className="h-card">{c.title}</h3>
              <p className="muted" style={{ marginTop: 8, fontSize: 14.5 }}>{c.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ── Solution ──
const Solution = () => {
  const cards = [
    { icon: "automation", title: "Automate repetitive work", body: "Replace manual hand-offs with reliable workflows that run in the background." },
    { icon: "agent", title: "Deploy AI agents", body: "Specialized agents that triage, summarize, route, and assist across operations." },
    { icon: "speed", title: "Improve lead response", body: "Catch and qualify every inbound in minutes, not hours — across channels." },
    { icon: "scale", title: "Scale paid acquisition", body: "Performance-led campaigns built to compound budgets, not just spend them." },
    { icon: "link", title: "Connect tools & workflows", body: "Stitch CRM, ads, email, and analytics into one continuous growth engine." },
    { icon: "chart", title: "Track performance with dashboards", body: "Real-time visibility into what's working — across channels and systems." },
  ];
  return (
    <section className="section" id="solution">
      <div className="container">
        <div className="section-head reveal">
          <div className="eyebrow">The Solution</div>
          <h2 className="h-section">We Build the Systems That Make Your Business Faster, Smarter, and More Profitable.</h2>
          <p className="lead">
            MLL Digital combines AI automation, agentic workflows, and digital marketing to build
            practical growth systems. The goal is simple: save time, reduce friction, improve execution,
            and create more revenue opportunities.
          </p>
        </div>
        <div className="grid-3">
          {cards.map((c, i) => (
            <div className="glass glass-card reveal" key={i} style={{ transitionDelay: `${(i % 3) * 80}ms` }}>
              <div className="icon-wrap"><Icon name={c.icon} /></div>
              <h3 className="h-card">{c.title}</h3>
              <p className="muted" style={{ marginTop: 8, fontSize: 14.5 }}>{c.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ── Services ──
const Services = () => {
  const items = [
    { icon: "automation", title: "AI Automations", body: "Automate repetitive tasks, internal workflows, lead handling, customer support, reporting, and business operations." },
    { icon: "agent",      title: "Agentic Workflows", body: "Build AI agents that analyze, assist, route, summarize, execute tasks, and support decision-making across the business." },
    { icon: "google",     title: "Google Ads", body: "Launch and optimize high-intent search campaigns designed to capture demand and scale profitably." },
    { icon: "meta",       title: "Meta Ads", body: "Full-funnel campaigns for Facebook and Instagram to generate leads, sales, and brand awareness." },
    { icon: "tiktok",     title: "TikTok Ads", body: "Creative-driven campaigns for attention, traffic, and scalable customer acquisition." },
    { icon: "pinterest",  title: "Pinterest Ads", body: "Help visual brands and e-commerce stores reach buyers through intent-driven discovery." },
    { icon: "seo",        title: "SEO", body: "Improve organic visibility with technical SEO, content strategy, and search-focused growth systems." },
    { icon: "social",     title: "Social Media Management", body: "Build a consistent content presence across key platforms with strategic planning and execution." },
    { icon: "mail",       title: "Email Marketing", body: "Automated email flows, campaigns, segmentation, and retention systems that compound." },
  ];
  return (
    <section className="section" id="services">
      <div className="container">
        <div className="section-head reveal">
          <div className="eyebrow">Services</div>
          <h2 className="h-section">Digital Growth Services Built Around AI, Automation, and Performance.</h2>
          <p className="lead">
            From intelligent workflows to paid acquisition, MLL Digital builds the systems
            businesses need to grow faster with less manual work.
          </p>
        </div>
        <div className="grid-3">
          {items.map((it, i) => (
            <div className="glass svc-card reveal" key={i} style={{ transitionDelay: `${(i % 3) * 70}ms` }}>
              <div className="head-row">
                <div className="icon-wrap"><Icon name={it.icon} /></div>
                <div className="num">0{i + 1}</div>
              </div>
              <h3 className="h-card">{it.title}</h3>
              <p className="desc">{it.body}</p>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "center", marginTop: 56 }} className="reveal">
          <PrimaryCTA label="Book a Discovery Call" />
        </div>
      </div>
    </section>
  );
};

// ── AI Systems with node-graph background ──
const AISystems = () => {
  const systems = [
    { pin: "01", icon: "lead",    title: "AI Lead Qualification Agent",     sub: "Score, route, and reply to inbound leads in minutes." },
    { pin: "02", icon: "support", title: "AI Customer Support Assistant",   sub: "Handle Tier-1 questions across email, chat, and inbox." },
    { pin: "03", icon: "report",  title: "AI Reporting Dashboard",          sub: "Pull live metrics into one explainable view, daily." },
    { pin: "04", icon: "sales",   title: "AI Sales Follow-Up System",       sub: "Personalized, multi-touch outreach without manual work." },
    { pin: "05", icon: "content", title: "AI Content Repurposing Workflow", sub: "Turn one long-form asset into a week of channel content." },
    { pin: "06", icon: "shop",    title: "AI E-commerce Operations Assistant", sub: "Inventory, listings, customer ops — quietly handled." },
    { pin: "07", icon: "star",    title: "AI Review & Reputation Monitoring", sub: "Surface, sort, and respond to feedback at scale." },
    { pin: "08", icon: "perf",    title: "AI Ad Performance Analysis Agent", sub: "Daily diagnostics on what's working and why." },
  ];
  return (
    <section className="section" id="systems">
      <div className="container">
        <div className="section-head reveal">
          <div className="eyebrow">AI Systems</div>
          <h2 className="h-section">AI Systems We Can Build For You.</h2>
          <p className="lead">
            Practical AI systems that reduce manual work, improve speed, and give your business more leverage.
          </p>
        </div>

        <div className="systems-canvas reveal">
          <svg className="systems-svg" viewBox="0 0 1000 600" preserveAspectRatio="none">
            <defs>
              <linearGradient id="wfGrad" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="#4d8bff" />
                <stop offset="100%" stopColor="#a855f7" />
              </linearGradient>
            </defs>
            {/* horizontal weaves */}
            <path className="wf-line" d="M 0 150 Q 250 80, 500 150 T 1000 150" />
            <path className="wf-line" d="M 0 300 Q 250 380, 500 300 T 1000 300" style={{ animationDelay: "-4s" }}/>
            <path className="wf-line" d="M 0 450 Q 250 380, 500 450 T 1000 450" style={{ animationDelay: "-8s" }}/>
            {/* verticals */}
            <path className="wf-line" d="M 250 0 Q 200 300, 250 600" style={{ animationDelay: "-2s" }}/>
            <path className="wf-line" d="M 750 0 Q 800 300, 750 600" style={{ animationDelay: "-6s" }}/>
          </svg>

          <div className="systems-grid">
            {systems.map((s, i) => (
              <div className="node reveal" key={i} style={{ transitionDelay: `${i * 50}ms` }}>
                <div className="pin"><span className="dot"></span>{s.pin}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{ width: 32, height: 32, borderRadius: 9, display: "grid", placeItems: "center",
                                background: "linear-gradient(135deg, rgba(77,139,255,0.18), rgba(168,85,247,0.12))",
                                border: "1px solid rgba(255,255,255,0.08)", color: "var(--blue)" }}>
                    <Icon name={s.icon} size={16} />
                  </div>
                  <div className="ttl">{s.title}</div>
                </div>
                <div className="sub">{s.sub}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

// ── Case Study ──
const CaseStudy = () => (
  <section className="section" id="case">
    <div className="container">
      <div className="section-head reveal">
        <div className="eyebrow">Case Study</div>
        <h2 className="h-section">From Ads to AI-Assisted Growth.</h2>
      </div>

      <div className="case-panel reveal">
        <div className="case-head">
          <div>
            <div className="big">€1.4M</div>
            <div className="eyebrow" style={{ marginTop: 14 }}>First-Year E-commerce Revenue</div>
          </div>
          <p className="sub">
            Through Google Ads, AI-supported analysis, and growth system optimization — generated in the
            first year for our own e-commerce store.
          </p>
        </div>

        <div className="case-metrics">
          <div className="metric"><div className="val">€1.4M</div><div className="lbl">First-Year Revenue</div></div>
          <div className="metric"><div className="val">Google Ads</div><div className="lbl">Primary Channel</div></div>
          <div className="metric"><div className="val">AI-Assisted</div><div className="lbl">Analysis & Optimization</div></div>
          <div className="metric"><div className="val">Year One</div><div className="lbl">Built from Zero</div></div>
        </div>

        <p className="disclaimer">Results vary by business model, offer, market, budget, and execution quality.</p>
      </div>

      <div style={{ display: "flex", justifyContent: "center", marginTop: 48 }} className="reveal">
        <PrimaryCTA label="Book a Discovery Call" />
      </div>
    </div>
  </section>
);

// ── Founder ──
const Founder = () => (
  <section className="section" id="founder">
    <div className="container">
      <div className="section-head reveal">
        <div className="eyebrow">Founder</div>
        <h2 className="h-section">Founder-Led, Operator-Minded.</h2>
      </div>

      <div className="glass founder reveal">
        <div className="founder-photo">[ FOUNDER PORTRAIT ]</div>
        <div>
          <p className="lead" style={{ fontSize: 19, color: "var(--ink)", margin: "0 0 22px" }}>
            MLL Digital was founded by Max — an e-commerce operator who combines performance marketing,
            automation, and AI systems to help businesses scale smarter.
          </p>
          <p className="muted" style={{ fontSize: 15, margin: 0 }}>
            The agency is built around practical execution: systems that save time, improve speed, and
            create measurable growth opportunities.
          </p>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 24 }}>
            {["Built from real e-commerce experience","Acquisition + automation","Practical outcomes","AI-first, commercially grounded"].map((t,i) => (
              <span key={i} style={{
                fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase",
                padding: "8px 14px", borderRadius: 999, border: "1px solid var(--line-2)",
                background: "rgba(255,255,255,0.03)", color: "var(--ink-2)"
              }}>{t}</span>
            ))}
          </div>
        </div>
      </div>
    </div>
  </section>
);

// ── Process timeline — JS-choreographed comet + strikes ──
const Process = () => {
  const steps = [
    { n: "01", t: "Discover",  d: "We analyze your business, tools, bottlenecks, marketing channels, and growth opportunities." },
    { n: "02", t: "Strategy",  d: "We define the highest-leverage AI and marketing systems to build first." },
    { n: "03", t: "Build",     d: "We create the automations, agents, campaigns, workflows, and tracking systems." },
    { n: "04", t: "Launch",    d: "We deploy the systems and ensure they work smoothly across your business." },
    { n: "05", t: "Optimize",  d: "We improve performance using data, feedback, and continuous testing." },
  ];

  const pulseRef = React.useRef(null);
  const fillRef  = React.useRef(null);
  const stepRefs = React.useRef([]);
  const railRef  = React.useRef(null);

  React.useEffect(() => {
    const CYCLE = 7000;                  // ms per full sweep
    const NODE_FRAC = [0.10, 0.30, 0.50, 0.70, 0.90]; // visual node positions along rail (0..1)
    const STRIKE_R = 0.018;              // trigger strike inside this radius
    const isVertical = () => window.matchMedia("(max-width: 900px)").matches;

    let raf = null;
    let active = true;
    let lastStruck = -1;          // last node index struck (per cycle)
    let lastCycle  = -1;          // which cycle we're in
    const start = performance.now();

    // Easing — smooth ease-in-out for premium feel
    const easeInOut = (x) => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2;

    const triggerStrike = (i) => {
      const el = stepRefs.current[i];
      if (!el) return;
      el.classList.remove("striking");
      // Force reflow so the same class can retrigger animations next cycle
      void el.offsetWidth;
      el.classList.add("striking");
      // Strip after the longest sub-animation ends
      window.setTimeout(() => el && el.classList.remove("striking"), 2800);
    };

    const tick = (now) => {
      if (!active) { raf = null; return; }
      const elapsed = now - start;
      const cycle = Math.floor(elapsed / CYCLE);
      const tt = (elapsed % CYCLE) / CYCLE;        // 0..1 inside cycle
      const t  = easeInOut(tt);                    // smoothed
      // Comet position in -0.08..1.08 (slight off-rail entry/exit)
      const pos = -0.08 + 1.16 * t;

      // Reset strike memory each new cycle
      if (cycle !== lastCycle) { lastCycle = cycle; lastStruck = -1; }

      const vertical = isVertical();

      // Update comet element — stays visible the whole sweep; circles naturally occlude it as it passes
      if (pulseRef.current) {
        let nearest = Infinity, nearestI = -1;
        for (let i = 0; i < NODE_FRAC.length; i++) {
          const d = Math.abs(pos - NODE_FRAC[i]);
          if (d < nearest) { nearest = d; nearestI = i; }
        }
        const inFrame = pos > -0.02 && pos < 1.02;
        pulseRef.current.style.opacity = inFrame ? "1" : "0";

        if (vertical) {
          pulseRef.current.style.transform = `translate(-50%, ${pos * 100 - 100}%)`;
          pulseRef.current.style.top = `${pos * 100}%`;
          pulseRef.current.style.left = "50%";
        } else {
          pulseRef.current.style.transform = `translate(-100%, -50%)`;
          pulseRef.current.style.left = `${pos * 100}%`;
          pulseRef.current.style.top = "50%";
        }

        // Strike when comet is at a node and not yet struck this cycle
        if (inFrame && nearest < STRIKE_R && nearestI > lastStruck) {
          lastStruck = nearestI;
          triggerStrike(nearestI);
        }
      }

      // Memory fill = how far the comet has traveled
      if (fillRef.current) {
        const fillPct = Math.max(0, Math.min(1, pos));
        if (vertical) {
          fillRef.current.style.height = `${fillPct * 100}%`;
          fillRef.current.style.width  = "100%";
        } else {
          fillRef.current.style.width  = `${fillPct * 100}%`;
          fillRef.current.style.height = "100%";
        }
      }

      raf = requestAnimationFrame(tick);
    };

    // Only run while process section is on-screen
    const sectionEl = document.getElementById("process");
    let io;
    const startLoop = () => { if (!raf) raf = requestAnimationFrame(tick); };
    const stopLoop  = () => { active = false; if (raf) cancelAnimationFrame(raf); raf = null; };
    if (sectionEl && "IntersectionObserver" in window) {
      io = new IntersectionObserver(([entry]) => {
        active = entry.isIntersecting;
        if (active) { active = true; startLoop(); }
      }, { threshold: 0.05 });
      io.observe(sectionEl);
      active = true; startLoop();
    } else {
      startLoop();
    }

    return () => { stopLoop(); io && io.disconnect(); };
  }, []);

  return (
    <section className="section" id="process">
      <div className="container">
        <div className="section-head reveal">
          <div className="eyebrow">Process</div>
          <h2 className="h-section">A Clear Process From Strategy to System.</h2>
        </div>
        <div className="process-wrap">
          <div className="process" ref={railRef}>
            <div className="process-rail" aria-hidden="true">
              <div className="base"></div>
              <div className="fill" ref={fillRef}></div>
              <div className="glow"></div>
              <div className="pulse" ref={pulseRef}></div>
            </div>
            {steps.map((s, i) => (
              <div className="step reveal" key={i} ref={el => (stepRefs.current[i] = el)} style={{ transitionDelay: `${i * 80}ms` }}>
                <div className="step-num">
                  <span className="halo"></span>
                  <span className="ring-burst"></span>
                  <span className="ring-burst-2"></span>
                  <span className="core-flash"></span>
                  <span className="num-text">{s.n}</span>
                </div>
                <h3>{s.t}</h3>
                <p>{s.d}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

// ── Why MLL ──
const WhyMLL = () => {
  const points = [
    "AI-first thinking",
    "Performance marketing experience",
    "Automation and acquisition combined",
    "Practical business systems, not hype",
    "Focus on time saved and revenue created",
    "Built for ambitious SMEs, e-commerce brands, coaches & consultants",
  ];
  return (
    <section className="section" id="why">
      <div className="container">
        <div className="why-grid">
          <div className="reveal">
            <div className="eyebrow" style={{ marginBottom: 18 }}>Why MLL Digital</div>
            <h2 className="h-section">Built for Businesses That Want to Move Before the Rest.</h2>
            <p className="lead">
              AI is not just a future trend. It is already changing how businesses operate, market,
              sell, and scale. MLL Digital helps businesses adopt the right systems early, without
              losing focus on practical execution and measurable growth.
            </p>
          </div>
          <div className="why-list reveal">
            {points.map((p, i) => (
              <div className="why-item" key={i} style={{ transitionDelay: `${i * 50}ms` }}>
                <div className="check"><Icon name="check" size={14} /></div>
                <div className="label">{p}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

// ── Final CTA ──
const FinalCTA = () => (
  <section className="section" id="book">
    <div className="container">
      <div className="final-cta reveal">
        <div className="eyebrow" style={{ justifyContent: "center", display: "inline-flex", marginBottom: 18 }}>Get Started</div>
        <h2 className="h-section gradient-text">Ready to Build Your AI-Powered Growth System?</h2>
        <p className="lead" style={{ textAlign: "center" }}>
          Book a Discovery Call and find out where AI, automation, and digital marketing can create
          the fastest impact in your business.
        </p>
        <div style={{ display: "flex", justifyContent: "center", marginTop: 8 }}>
          <PrimaryCTA label="Book a Discovery Call" />
        </div>
        <div className="microcopy">No pressure. Just a strategic look at what can be automated, optimized, and scaled.</div>
      </div>
    </div>
  </section>
);

// ── Footer ──
const Footer = () => (
  <footer id="contact">
    <div className="container">
      <div className="footer-grid">
        <div>
          <div className="footer-brand">
            <img src="assets/mll-logo.png" alt="MLL Digital" />
          </div>
          <p className="footer-tagline">AI Automation & Digital Growth Systems.</p>
        </div>
        <div>
          <h4>Navigate</h4>
          <div className="footer-links">
            <a href="#services">Services</a>
            <a href="#systems">AI Systems</a>
            <a href="#case">Case Study</a>
            <a href="#process">Process</a>
          </div>
        </div>
        <div>
          <h4>Contact</h4>
          <div className="footer-links">
            <a href="mailto:hello@mlldigital.com">hello@mlldigital.com</a>
            <a href="#linkedin">LinkedIn</a>
            <a href="#instagram">Instagram</a>
          </div>
        </div>
        <div>
          <h4>Legal</h4>
          <div className="footer-links">
            <a href="#privacy">Privacy Policy</a>
            <a href="#terms">Terms</a>
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 MLL Digital · All rights reserved</span>
        <span>Built for businesses moving before the rest.</span>
      </div>
    </div>
  </footer>
);

Object.assign(window, { Problem, Solution, Services, AISystems, CaseStudy, Founder, Process, WhyMLL, FinalCTA, Footer });
