// Sections: services, logos, case studies, testimonial, comparison, FAQ, calendly

const fakeLogos = [
  { name: "Northwind", glyph: "◢" },
  { name: "Statsig", glyph: "▣" },
  { name: "Loop", glyph: "◯" },
  { name: "Cobalt", glyph: "◆" },
  { name: "Helix", glyph: "✦" },
  { name: "Parallel", glyph: "▤" },
  { name: "Vector", glyph: "▶" },
  { name: "Anvil", glyph: "◣" },
  { name: "Kestrel", glyph: "◭" },
  { name: "Mosaic", glyph: "▦" },
];

const LogoStrip = () => {
  const items = [...fakeLogos, ...fakeLogos];
  return (
    <div className="logos">
      <div className="logos-track">
        {items.map((l, i) => (
          <span className="logo-item" key={i}>
            <span className="logo-mark" style={{ color: ["#ff3366","#ff8c42","#ffd23f","#06d6a0","#3a86ff"][i % 5] }}>
              {l.glyph}
            </span>
            {l.name}
          </span>
        ))}
      </div>
    </div>
  );
};

// Custom mini SVG icons for each service
const ServiceIcon = ({ kind }) => {
  const c = "#ff8c42";
  if (kind === "implementation") {
    return (
      <svg viewBox="0 0 56 56" width="56" height="56">
        <rect x="6" y="6" width="14" height="14" rx="3" fill="none" stroke={c} strokeWidth="1.5"/>
        <rect x="36" y="6" width="14" height="14" rx="3" fill="none" stroke="#06d6a0" strokeWidth="1.5"/>
        <rect x="6" y="36" width="14" height="14" rx="3" fill="none" stroke="#ffd23f" strokeWidth="1.5"/>
        <rect x="36" y="36" width="14" height="14" rx="3" fill="#ff8c42" stroke="#ff8c42"/>
        <line x1="20" y1="13" x2="36" y2="13" stroke="rgba(255,255,255,0.3)" strokeDasharray="2 2"/>
        <line x1="13" y1="20" x2="13" y2="36" stroke="rgba(255,255,255,0.3)" strokeDasharray="2 2"/>
        <line x1="43" y1="20" x2="43" y2="36" stroke="rgba(255,255,255,0.3)" strokeDasharray="2 2"/>
        <line x1="20" y1="43" x2="36" y2="43" stroke="rgba(255,255,255,0.3)" strokeDasharray="2 2"/>
      </svg>
    );
  }
  if (kind === "migration") {
    return (
      <svg viewBox="0 0 56 56" width="56" height="56">
        <ellipse cx="12" cy="14" rx="9" ry="4" fill="none" stroke="#3a86ff" strokeWidth="1.5"/>
        <path d="M3 14 L3 32 Q3 36 12 36 Q21 36 21 32 L21 14" fill="none" stroke="#3a86ff" strokeWidth="1.5"/>
        <ellipse cx="12" cy="24" rx="9" ry="4" fill="none" stroke="#3a86ff" strokeWidth="1" opacity="0.5"/>
        <ellipse cx="44" cy="22" rx="9" ry="4" fill="none" stroke="#ff8c42" strokeWidth="1.5"/>
        <path d="M35 22 L35 40 Q35 44 44 44 Q53 44 53 40 L53 22" fill="none" stroke="#ff8c42" strokeWidth="1.5"/>
        <ellipse cx="44" cy="32" rx="9" ry="4" fill="none" stroke="#ff8c42" strokeWidth="1" opacity="0.5"/>
        <path d="M22 25 L34 25" stroke="#ffd23f" strokeWidth="1.5" markerEnd="url(#arrowSvc)"/>
        <defs>
          <marker id="arrowSvc" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="5" markerHeight="5" orient="auto">
            <path d="M0 0 L10 5 L0 10 z" fill="#ffd23f"/>
          </marker>
        </defs>
      </svg>
    );
  }
  if (kind === "custom") {
    return (
      <svg viewBox="0 0 56 56" width="56" height="56">
        <path d="M14 18 L6 28 L14 38" fill="none" stroke="#ff3366" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <path d="M42 18 L50 28 L42 38" fill="none" stroke="#ff3366" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        <line x1="32" y1="14" x2="24" y2="42" stroke="#ff8c42" strokeWidth="2" strokeLinecap="round"/>
      </svg>
    );
  }
  if (kind === "audit") {
    return (
      <svg viewBox="0 0 56 56" width="56" height="56">
        <circle cx="24" cy="24" r="14" fill="none" stroke="#ffd23f" strokeWidth="1.5"/>
        <line x1="34" y1="34" x2="46" y2="46" stroke="#ffd23f" strokeWidth="2" strokeLinecap="round"/>
        <line x1="18" y1="22" x2="30" y2="22" stroke="rgba(255,210,63,0.6)" strokeWidth="1.5"/>
        <line x1="18" y1="26" x2="26" y2="26" stroke="rgba(255,210,63,0.4)" strokeWidth="1.5"/>
        <line x1="18" y1="30" x2="28" y2="30" stroke="rgba(255,210,63,0.6)" strokeWidth="1.5"/>
      </svg>
    );
  }
  // ongoing
  return (
    <svg viewBox="0 0 56 56" width="56" height="56">
      <circle cx="28" cy="28" r="18" fill="none" stroke="#06d6a0" strokeWidth="1.5"/>
      <path d="M28 12 A16 16 0 0 1 44 28" fill="none" stroke="#06d6a0" strokeWidth="3" strokeLinecap="round"/>
      <circle cx="28" cy="28" r="3" fill="#06d6a0"/>
    </svg>
  );
};

const services = [
  {
    kind: "implementation",
    num: "01",
    title: "HubSpot Implementation",
    desc: "Net-new HubSpot setup tailored to your GTM motion. Lifecycle stages, lead scoring, deal pipelines, custom objects, properties, and the workflows that tie it together.",
    timeline: "3–6 weeks",
    range: "$8k–25k",
  },
  {
    kind: "migration",
    num: "02",
    title: "Salesforce / Pardot Migration",
    desc: "Move off Pardot or Salesforce without losing attribution data, automation logic, or campaign history. Field mapping, data dedup, parallel-run validation.",
    timeline: "4–8 weeks",
    range: "$12k–40k",
  },
  {
    kind: "custom",
    num: "03",
    title: "Custom Development",
    desc: "Custom objects, CRM cards, UI extensions, server-side automation in TypeScript, and integrations to product DBs, billing, and your data warehouse.",
    timeline: "Project-based",
    range: "$150/hr",
  },
  {
    kind: "audit",
    num: "04",
    title: "Audit & Cleanup",
    desc: "We map every workflow, list, property, and integration. You get a prioritized fix-list, a portal hygiene score, and a 90-day remediation plan.",
    timeline: "1–2 weeks",
    range: "$2.5k flat",
  },
  {
    kind: "ongoing",
    num: "05",
    title: "Ongoing HubSpot Admin",
    desc: "Fractional senior admin on retainer. Workflow changes, reporting, lifecycle adjustments, sequence builds, and Slack-channel SLA.",
    timeline: "Monthly",
    range: "$4k/mo",
  },
  {
    kind: "implementation",
    num: "06",
    title: "Reporting & Attribution",
    desc: "Multi-touch attribution that actually reconciles. Custom report builder dashboards, revenue attribution, and pipeline forecasting that your CFO trusts.",
    timeline: "2–4 weeks",
    range: "$6k–15k",
  },
];

const Services = () => (
  <section className="block" id="services">
    <div className="container">
      <div className="section-header">
        <div>
          <div className="section-eyebrow">
            <span className="section-eyebrow-num">01 ·</span> Services
          </div>
          <h2 className="section-title">What we <em>actually</em> build.</h2>
        </div>
        <p className="section-desc">
          Every engagement starts with the question your last vendor didn't ask:
          what does "working" mean for your revenue team? Then we build to that, not to a checklist.
        </p>
      </div>
      <div className="services-grid">
        {services.map(s => (
          <div className="service-card" key={s.num}>
            <div className="service-num">{s.num} / 06</div>
            <ServiceIcon kind={s.kind} />
            <h3>{s.title}</h3>
            <p>{s.desc}</p>
            <div className="service-meta">
              <span>Timeline · <strong>{s.timeline}</strong></span>
              <span><strong>{s.range}</strong></span>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

// CASE STUDIES
const caseStudies = [
  {
    stat: "60",
    suffix: "%",
    color: "green",
    headline: "Reduced lead-to-MQL time from 14 days to 5.6 days.",
    industry: "B2B SaaS · Series B",
    tag: "Workflows · Lead Scoring",
    full: {
      client: "Series B observability platform",
      stats: [
        { num: "60%", lbl: "Faster MQL" },
        { num: "3.2x", lbl: "SDR throughput" },
        { num: "$2.4M", lbl: "Pipeline / Q" },
      ],
      situation: "Inbound leads sat in 'New' for an average of 14 days because routing depended on a daily CSV pull from product. Marketing couldn't show source ROI. Sales blamed marketing. Marketing blamed Pardot.",
      did: [
        ["Replaced CSV pull", "real-time webhook + custom object"],
        ["Rebuilt scoring", "behavioral × firmographic, decay weighted"],
        ["Round-robin", "by territory + capacity, with PTO awareness"],
        ["Salesforce sync", "bidirectional, 2-min cadence"],
      ],
      outcome: "Average lead-to-MQL dropped to 5.6 days. SDRs moved from 80 to 260 outbound touches/week because their queue was actually triaged. Attribution became the source of truth for the QBR.",
    },
  },
  {
    stat: "80",
    suffix: "k",
    color: "orange",
    headline: "Migrated 80,000 contacts off Salesforce + Pardot in 3 weeks.",
    industry: "Professional Services · 200 employees",
    tag: "Migration · Attribution",
    full: {
      client: "Boutique consulting firm, 80k contacts, 14 years of Pardot history",
      stats: [
        { num: "0", lbl: "Records lost" },
        { num: "3 wks", lbl: "Cutover" },
        { num: "100%", lbl: "Campaign history retained" },
      ],
      situation: "Pardot renewal was 4x last year's price. They had 14 years of campaign history, custom email templates, and 6 Salesforce automations they couldn't explain. Previous agency quoted 9 months.",
      did: [
        ["Field map", "212 SF fields → 178 HS properties"],
        ["Dedup pass", "merged 4,200 duplicate contacts"],
        ["Parallel run", "2 weeks shadow-syncing both systems"],
        ["Sunset plan", "Pardot read-only for 90 days post-cutover"],
      ],
      outcome: "Cut over on a Friday night. Marketing sent first HubSpot campaign Monday morning. Saved $94k in renewal cost. The CMO described the migration as 'the most boring weekend of my year' — exactly what we promised.",
    },
  },
  {
    stat: "4.2",
    suffix: "x",
    color: "red",
    headline: "Rebuilt attribution. CFO finally trusts the marketing dashboard.",
    industry: "B2B SaaS · Series A",
    tag: "Reporting · Custom Dev",
    full: {
      client: "Series A vertical SaaS, ~$8M ARR",
      stats: [
        { num: "4.2x", lbl: "ROI clarity" },
        { num: "12", lbl: "Custom reports" },
        { num: "1", lbl: "Source of truth" },
      ],
      situation: "Marketing reported $4.1M in pipeline. Sales reported $1.3M. Finance reported $2.6M. Each pulled from a different lifecycle definition and the multi-touch model double-counted self-sourced opps.",
      did: [
        ["Lifecycle stages", "rewrote definitions, locked behind workflow"],
        ["Custom report", "single attribution model, weighted, governed"],
        ["Snapshot table", "weekly, immutable, audit trail"],
        ["CFO dashboard", "matches the GL, reconciled monthly"],
      ],
      outcome: "Marketing, sales, and finance now meet in the same dashboard with the same number. The CFO renewed marketing budget for the first time in two years without a 90-minute defense session.",
    },
  },
];

const CaseStudyModal = ({ data, onClose }) => (
  <div className="modal-overlay" onClick={onClose}>
    <div className="modal" onClick={e => e.stopPropagation()}>
      <button className="modal-close" onClick={onClose} aria-label="Close">
        <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 1 L13 13 M13 1 L1 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
      </button>
      <div className="modal-eyebrow">Case Study · {data.full.client}</div>
      <h3>{data.headline}</h3>
      <div className="modal-stats">
        {data.full.stats.map(s => (
          <div className="modal-stat" key={s.lbl}>
            <div className="num">{s.num}</div>
            <div className="lbl">{s.lbl}</div>
          </div>
        ))}
      </div>
      <div className="modal-section">
        <h5>The Situation</h5>
        <p>{data.full.situation}</p>
      </div>
      <div className="modal-section">
        <h5>What we built</h5>
        <ul>
          {data.full.did.map((d, i) => (
            <li key={i}><span>{d[0]}</span><strong>{d[1]}</strong></li>
          ))}
        </ul>
      </div>
      <div className="modal-section">
        <h5>The Outcome</h5>
        <p>{data.full.outcome}</p>
      </div>
    </div>
  </div>
);

const CaseStudies = () => {
  const [open, setOpen] = React.useState(null);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpen(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);
  return (
    <section className="block" id="case-studies">
      <div className="container">
        <div className="section-header">
          <div>
            <div className="section-eyebrow"><span className="section-eyebrow-num">02 ·</span> Case Studies</div>
            <h2 className="section-title">Receipts, not <em>vibes</em>.</h2>
          </div>
          <p className="section-desc">
            Three recent engagements. Click any card for the full breakdown — situation, what we built, what changed.
          </p>
        </div>
        <div className="case-grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))" }}>
          {caseStudies.map((c, i) => (
            <div className="case-card" key={i} onClick={() => setOpen(i)}>
              <div className={`case-stat ${c.color}`}>
                {c.stat}<span className="case-stat-suffix">{c.suffix}</span>
              </div>
              <h4>{c.headline}</h4>
              <p>{c.industry}</p>
              <div className="case-meta">
                <span className="case-tag">→ {c.tag}</span>
                <span className="case-cta">Read case study</span>
              </div>
            </div>
          ))}
        </div>
      </div>
      {open !== null && <CaseStudyModal data={caseStudies[open]} onClose={() => setOpen(null)} />}
    </section>
  );
};

const Testimonial = () => (
  <section className="block">
    <div className="container">
      <div className="testimonial">
        <p className="testimonial-quote">
          "We'd been through two HubSpot agencies before Chroma. The difference is they actually understood what
          a <em>lifecycle stage</em> means to my CFO. Six weeks in, our attribution finally <em>reconciles</em>."
        </p>
        <div className="testimonial-attr">
          <div className="testimonial-avatar">MK</div>
          <div className="testimonial-name">
            <div>Maya Krishnan</div>
            <div className="role">VP RevOps · Northwind</div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const compareRows = [
  { label: "Senior HubSpot expertise", us: "✓", solo: "partial", agency: "✓" },
  { label: "Speaks RevOps fluently", us: "✓", solo: "partial", agency: "✗" },
  { label: "Custom dev (CRM cards, APIs)", us: "✓", solo: "✗", agency: "partial" },
  { label: "Project lead with skin in the game", us: "✓", solo: "✓", agency: "✗" },
  { label: "Multi-touch attribution that reconciles", us: "✓", solo: "partial", agency: "partial" },
  { label: "Salesforce migration playbook", us: "✓", solo: "✗", agency: "✓" },
  { label: "Typical timeline to first MQL routing", us: "2 weeks", solo: "6 weeks", agency: "8 weeks" },
  { label: "Typical project cost", us: "$8–25k", solo: "$3–10k", agency: "$60–150k" },
  { label: "AI-augmented delivery", us: "✓", solo: "✗", agency: "✗" },
];

const renderCell = (v) => {
  if (v === "✓") return <span className="check">✓</span>;
  if (v === "✗") return <span className="cross">—</span>;
  if (v === "partial") return <span className="partial">~</span>;
  return v;
};

const Compare = () => (
  <section className="block" id="compare">
    <div className="container">
      <div className="section-header">
        <div>
          <div className="section-eyebrow"><span className="section-eyebrow-num">03 ·</span> Why us</div>
          <h2 className="section-title">Pick your <em>poison</em>.</h2>
        </div>
        <p className="section-desc">
          Solo freelancers are cheap until they ghost. Big agencies are thorough until your AE rotates.
          We're built for the middle: senior, technical, accountable.
        </p>
      </div>
      <div className="compare-wrap">
        <table className="compare-table">
          <thead>
            <tr>
              <th></th>
              <th className="us">CHROMA</th>
              <th>Solo Freelancer</th>
              <th>Big Agency</th>
            </tr>
          </thead>
          <tbody>
            {compareRows.map((r, i) => (
              <tr key={i}>
                <td className="row-label">{r.label}</td>
                <td className="us-cell">{renderCell(r.us)}</td>
                <td className="dim">{renderCell(r.solo)}</td>
                <td className="dim">{renderCell(r.agency)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </section>
);

const faqs = [
  { q: "Are you a HubSpot certified partner?", a: "Yes — Diamond Solutions Partner, with 14 individual certifications across the team (Marketing Hub Implementation, Sales Hub Implementation, CMS Developer, Data Integrations, Reporting). We're listed in HubSpot's partner directory under the agency name Chroma." },
  { q: "How fast can you start?", a: "For audits and clean-ups, usually within a week. For full implementations, we run a 2-week kickoff after contract signature — discovery, technical scope, and a fixed statement of work before any portal changes happen." },
  { q: "Do you work with Salesforce alongside HubSpot?", a: "Yes. About 60% of our engagements involve a HubSpot ↔ Salesforce sync. We've built bidirectional integrations using HubSpot's native sync, custom middleware, and direct API work where the native tooling falls short." },
  { q: "What does 'AI-augmented' mean here?", a: "We use AI heavily for the boring parts: data dedup logic, field mapping, generating workflow scaffolds, draft documentation, and writing custom code (CRM cards, UI extensions). It's not a buzzword — it's what lets a 6-person team ship at the pace of a 25-person agency. A senior human reviews everything before it touches your portal." },
  { q: "Do you offer fixed-price or hourly?", a: "Both. Audits are fixed ($2,500). Implementations and migrations are fixed-price after a paid discovery. Custom development is $150/hr with weekly cap reporting. Retainers are flat $4k/month with a defined hour bank." },
  { q: "What happens after the project ends?", a: "Two options. (1) You're trained up and we hand over a runbook, or (2) you put us on a retainer and we own the portal as your fractional admin. About 70% of clients pick option 2, but we don't push it." },
];

const FAQ = () => {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="block" id="faq">
      <div className="container">
        <div className="section-header">
          <div>
            <div className="section-eyebrow"><span className="section-eyebrow-num">04 ·</span> FAQ</div>
            <h2 className="section-title">Things people <em>actually</em> ask.</h2>
          </div>
          <p className="section-desc">
            If your question isn't here, it's a good sign it's worth asking on the call.
          </p>
        </div>
        <div className="faq-list">
          {faqs.map((f, i) => (
            <div className={`faq-item ${open === i ? "open" : ""}`} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{f.q}</span>
                <span className="faq-toggle">
                  <svg width="12" height="12" viewBox="0 0 12 12">
                    <path d="M6 1 V11 M1 6 H11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                  </svg>
                </span>
              </button>
              <div className="faq-a">{f.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// Calendly
const CalendlyMock = () => {
  const [selected, setSelected] = React.useState(11);
  const dows = ["S","M","T","W","T","F","S"];
  // first day of month: a Wednesday for prettiness
  const offset = 3;
  const days = Array.from({ length: 35 }, (_, i) => i - offset + 1).map(n => n > 0 && n <= 30 ? n : null);
  const availableDays = [4, 5, 6, 11, 12, 13, 18, 19, 20, 25, 26, 27];
  const today = 8;
  const times = ["9:00 AM", "9:30 AM", "10:30 AM", "11:00 AM", "1:00 PM", "1:30 PM", "2:00 PM", "3:00 PM", "3:30 PM", "4:00 PM"];

  return (
    <div className="cal-mock">
      <div className="cal-mock-header">
        <div className="cal-avatar">DH</div>
        <div className="cal-mock-title">
          <strong>30-min Discovery Call</strong>
          Daniel Huang · Founder, Chroma
        </div>
      </div>
      <div className="cal-month">
        <button className="cal-arrow">‹</button>
        <span>May 2026</span>
        <button className="cal-arrow">›</button>
      </div>
      <div className="cal-grid">
        {dows.map((d, i) => <div key={i} className="cal-dow">{d}</div>)}
        {days.map((d, i) => {
          if (d === null) return <div key={i}></div>;
          const avail = availableDays.includes(d);
          const isSel = d === selected;
          const isToday = d === today;
          return (
            <button
              key={i}
              className={`cal-day ${avail ? "avail" : ""} ${isSel ? "selected" : ""} ${isToday ? "today" : ""}`}
              onClick={() => avail && setSelected(d)}
              disabled={!avail}
            >
              {d}
            </button>
          );
        })}
      </div>
      <div className="cal-times">
        {times.map(t => (
          <button key={t} className="cal-time">{t}</button>
        ))}
      </div>
    </div>
  );
};

const BookCall = () => (
  <section className="block" id="book">
    <div className="container">
      <div className="calendly-wrap">
        <div className="calendly-side">
          <div className="section-eyebrow"><span className="section-eyebrow-num">05 ·</span> Book a call</div>
          <h2>Thirty minutes. <em>No pitch.</em></h2>
          <p>
            Tell us what's broken — lead routing, attribution, a stalled migration, a portal you inherited.
            We'll tell you whether we can help, what it would cost, and what we'd build first.
          </p>
          <p>
            If we're not the right fit, we'll say so on the call and recommend who is.
          </p>
          <ul className="calendly-bullets">
            <li>Senior HubSpot engineer on the call (not a salesperson)</li>
            <li>You leave with a sketched scope, not a follow-up email</li>
            <li>NDAs sent in advance on request</li>
          </ul>
        </div>
        <div className="calendly-embed">
          <CalendlyMock />
        </div>
      </div>
    </div>
  </section>
);

window.LogoStrip = LogoStrip;
window.Services = Services;
window.CaseStudies = CaseStudies;
window.Testimonial = Testimonial;
window.Compare = Compare;
window.FAQ = FAQ;
window.BookCall = BookCall;
