// Pricing.jsx — "Price the website your business actually needs."
// Redesigned selection UI (site-type cards + campaign landing card) over the
// same estimate math: setup scales with pages, +$800/landing page, monthly vs
// year-upfront (10% off, reframed as a savings line). Request form unchanged.
const PR_USD = (n) => "$" + Math.round(n).toLocaleString("en-US");

const PR_SITE_TYPES = [
  { id: "focused", t: "Focused one-page site", d: "For a simple presence or single high-value offer.", pages: 1 },
  { id: "core", t: "Core business site", d: "Best fit for most established businesses.", pages: 5 },
  { id: "expanded", t: "Expanded service site", d: "For multiple services, audiences, or locations.", pages: 8 },
  { id: "expanded2", t: "Expanded service site", d: "For multiple services, audiences, or locations.", pages: 8 },
];

// compact +/- stepper matching the new design
function PeStepper({ value, set, min, max, label, hook }) {
  return (
    <div className="pe-step" data-hook={hook} onClick={(e) => e.stopPropagation()}>
      <button type="button" className="pe-step-btn" data-hook={hook ? hook + "-dec" : undefined} onClick={() => set(Math.max(min, value - 1))} disabled={value <= min} aria-label={"Decrease " + label}>&minus;</button>
      <span className="pe-step-val" data-hook={hook ? hook + "-value" : undefined}>{value}</span>
      <button type="button" className="pe-step-btn" data-hook={hook ? hook + "-inc" : undefined} onClick={() => set(Math.min(max, value + 1))} disabled={value >= max} aria-label={"Increase " + label}>+</button>
    </div>
  );
}

function PrPill() { return null; }

function PayRow({ k, v, accent, strong }) {
  return (
    <div className={"pay-row" + (strong ? " pay-row--total" : "")}>
      <span className="pay-row-k">{k}</span>
      <span className={"pay-row-v" + (accent ? " pay-row-v--" + accent : "")}>{v}</span>
    </div>
  );
}

function Pricing({ onSelect }) {
  const beacon = useBeaconChat();
  const [siteType, setSiteType] = useState("focused");
  const [pages, setPages] = useState(1);
  const [addLanding, setAddLanding] = useState(false);
  const [landing, setLanding] = useState(1);
  const [sel, setSel] = useState(null);
  const [sent, setSent] = useState(false);
  const formRef = useRef(null);
  const headRef = useReveal();
  const modRef = useReveal();
  const formReveal = useReveal();

  const stdSetup = (p) => {
    const t = { 1: 1000, 2: 1250, 3: 1350, 4: 1450, 5: 1500 };
    return p <= 5 ? t[Math.max(1, p)] : 1500 + (p - 5) * 250;
  };
  const landingCount = addLanding ? landing : 0;
  const landingCost = landingCount * 800;
  const setupFee = stdSetup(pages) + landingCost;
  const monthlyFY = setupFee + 199 * 12;
  const annualFY = Math.round(monthlyFY * 0.9);
  const annualSavings = monthlyFY - annualFY;
  const siteAfterSavings = setupFee - annualSavings;
  const extraStd = Math.max(0, pages - 5);

  const pickType = (ty) => { setSiteType(ty.id); setPages(ty.pages); };

  const onMove = (e) => {
    const el = e.currentTarget;
    const r = el.getBoundingClientRect();
    el.style.setProperty("--mx", `${e.clientX - r.left}px`);
    el.style.setProperty("--my", `${e.clientY - r.top}px`);
  };

  const heartCheck = (
    <svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ filter: "drop-shadow(0 1px 2px rgba(0,0,0,0.4))" }} aria-hidden="true">
      <path d="M12 21C12 21 3.5 15.6 3.5 9.2C3.5 6.6 5.6 4.6 8.1 4.6C9.8 4.6 11.2 5.6 12 7C12.8 5.6 14.2 4.6 15.9 4.6C18.4 4.6 20.5 6.6 20.5 9.2C20.5 15.6 12 21 12 21Z" />
      <path d="M8.5 11L11 13.5L15.5 8.8" />
    </svg>
  );
  const valueProps = [
    { i: "ri-flashlight-fill", t: "Ready in less than a week" },
    { i: "ri-search-eye-line", t: "Ready for Search and AI discoverability" },
    { i: "ri-cursor-line", t: "Designed to convert visitors" },
    { svg: heartCheck, t: "Monthly care after launch" },
  ];

  const pagesLabel = `${pages} standard page${pages > 1 ? "s" : ""}${landingCount ? ` + ${landingCount} landing page${landingCount > 1 ? "s" : ""}` : ""}`;
  const choose = (plan) => {
    const est = { plan, pages, landingCount, landingCost, setupFee, monthlyFY, annualFY, annualSavings, siteAfterSavings, pagesLabel, selectedAt: Date.now() };
    setSel(est);
    if (onSelect) onSelect(est);
    if (beacon && beacon.openFullscreen) beacon.openFullscreen();
    else window.dispatchEvent(new CustomEvent("siteworks:open-beacon"));
  };

  return (
    <section id="review" className="section pr-sec">
      <div className="haze-bloom" style={{ opacity: 0.12 }} aria-hidden="true" />
      <div className="wrap" style={{ position: "relative" }}>
        {/* intro */}
        <div ref={headRef} className="reveal pr-hero">
          <div className="eyebrow pr-eyebrow"><span className="dot" />Pricing</div>
          <h2 className="h-section pr-h2">Price the website your business actually needs.</h2>
          <p className="p-lead pr-sub">Pick the closest site scope, add campaign pages if needed, and compare the clearest way to launch: lower upfront cost with monthly care, or the best first-year value in one payment.</p>

          <div className="pr-vp-grid">
            {valueProps.map((v, i) => {
              const tone = i % 2 === 0 ? "magenta" : "violet";
              return (
                <div key={v.t} className="pr-vp-item">
                  {v.svg
                    ? <span className={"orb orb-" + tone} style={{ width: 42, height: 42 }}>{v.svg}</span>
                    : <Orb icon={v.i} tone={tone} size={42} />}
                  <span className="wc-label">{v.t}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* estimate module */}
        <div ref={modRef} className="reveal pe-module">
          <div className="pe-flowstep pe-flowstep--build">
          <div className="pe-head">
            <div className="pe-head-text">
              <h3 className="pe-title">1. Build your estimate</h3>
              <p className="pe-sub">Start with the site type that fits your business. We&rsquo;ll confirm the final scope after reviewing your current site and homepage opportunity.</p>
            </div>
            <span className="pe-stat-pill"><span className="pe-stat-dot" />Starts at $1,000 + $199/mo</span>
          </div>

          <div className="pe-divider" />

          <div className="pe-q">
            <h4 className="pe-q-title">What kind of site are you looking for?</h4>
            <p className="pe-q-sub">Choose the closest starting point. You can fine-tune pages after.</p>
          </div>

          {/* selection */}
          <div className="pe-selector">
            <div className="pe-types" data-hook="standard-page-selector">
              {PR_SITE_TYPES.map((ty) => {
                const on = siteType === ty.id;
                return (
                  <div key={ty.id} className={"pe-card" + (on ? " is-on" : "")} onClick={() => pickType(ty)} role="radio" aria-checked={on} tabIndex={0}
                    onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pickType(ty); } }}>
                    <div className="pe-card-main">
                      <span className="pe-radio" aria-hidden="true" />
                      <div className="pe-card-body">
                        <div className="pe-card-t">{ty.t}</div>
                        <div className="pe-card-d">{ty.d}</div>
                      </div>
                    </div>
                    {on && (
                      <div className="pe-card-stepper">
                        <span className="pe-step-lbl">Number of pages</span>
                        <PeStepper value={pages} set={setPages} min={1} max={20} label="pages" hook="standard-pages" />
                      </div>
                    )}
                  </div>
                );
              })}
            </div>

            <div className="pe-landing-wrap">
              <div className={"pe-card pe-card--landing" + (addLanding ? " is-on" : "")} data-hook="landing-toggle" onClick={() => setAddLanding(!addLanding)} role="checkbox" aria-checked={addLanding} tabIndex={0}
                onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setAddLanding(!addLanding); } }}>
                <div className="pe-card-main">
                  <span className="pe-checkbox" aria-hidden="true"><i className="ri-check-line" /></span>
                  <div className="pe-card-body">
                    <div className="pe-card-t">Do you need a campaign landing page?</div>
                  </div>
                </div>
                {addLanding && (
                  <React.Fragment>
                    <div className="pe-land-divider" />
                    <p className="pe-land-desc">$800 each. Best for a specific offer, ad campaign, launch, or sales page that needs its own message and CTA.</p>
                    <div className="pe-card-stepper">
                      <span className="pe-step-lbl">Number of landing pages</span>
                      <PeStepper value={landing} set={setLanding} min={1} max={10} label="landing pages" hook="landing-count" />
                    </div>
                  </React.Fragment>
                )}
              </div>
            </div>
          </div>

          </div>{/* /pe-flowstep--build */}

          <div className="pe-flowstep pe-flowstep--pay">
          {/* payment options */}
          <h4 className="pe-pay-title">2. Choose your payment options.</h4>
          <div className="pay-cards">
            {/* monthly */}
            <div className="pay-card pay-card--monthly" data-hook="monthly-card">
              <div className="pay-card-head">
                <h5 className="pay-card-title">Website + Monthly Care</h5>
                <span className="pay-badge pay-badge--violet"><span className="pay-badge-dot" />Most Popular</span>
              </div>
              <div className="pay-price-label">Cost of site</div>
              <div className="pay-price">{PR_USD(setupFee)}</div>
              <p className="pay-desc">Best when you want the site live with a smaller starting payment.</p>
              <div className="pay-rows">
                <PayRow k="Cost of site" v={PR_USD(setupFee)} />
                <PayRow k="Due upfront" v={PR_USD(setupFee)} />
                <PayRow k="Monthly Site Care & Updates" v="$199/mo" />
                <PayRow k="Add-ons" v={landingCost ? PR_USD(landingCost) : "$0"} />
                <PayRow k="First-year total" v={PR_USD(monthlyFY)} strong />
              </div>
              <button type="button" className="btn btn-secondary" data-hook="monthly-cta" style={{ width: "100%", marginTop: "auto", justifyContent: "center" }} onClick={() => choose("monthly")}>Build my homepage prototype</button>
            </div>

            {/* year — featured */}
            <div className="pay-card pay-card--year" data-hook="year-card">
              <span className="pay-year-glow" aria-hidden="true" />
              <div className="pay-card-inner">
                <div className="pay-card-head">
                  <h5 className="pay-card-title">Website + Year Care</h5>
                  <span className="pay-badge pay-badge--orange"><span className="pay-badge-dot" />Best Value</span>
                </div>
                <div className="pay-price-label">Cost of site after savings</div>
                <div className="pay-price">{PR_USD(siteAfterSavings)}</div>
                <p className="pay-desc">Best when you want to launch and want to save by paying for the year upfront.</p>
                <div className="pay-rows">
                  <PayRow k="Cost of site before savings" v={PR_USD(setupFee)} />
                  <PayRow k="Upfront payment savings" v={PR_USD(annualSavings)} accent="orange" />
                  <PayRow k="Cost of site after savings" v={PR_USD(siteAfterSavings)} />
                  <PayRow k="Monthly Site Care & Updates" v="Included for the year" />
                  <PayRow k="Due upfront" v={PR_USD(annualFY)} />
                  <PayRow k="First-year total" v={PR_USD(annualFY)} strong />
                </div>
                <button type="button" className="btn btn-primary" data-hook="year-cta" style={{ width: "100%", marginTop: "auto", justifyContent: "center" }} onClick={() => choose("annual")}>Build my homepage prototype <i className="ri-arrow-right-line" /></button>
              </div>
            </div>
          </div>

          </div>{/* /pe-flowstep--pay */}

          <p className="pe-fineprint">This estimate covers standard marketing pages. Ecommerce, booking systems, memberships, custom apps, and complex integrations are reviewed separately.</p>
        </div>
      </div>
    </section>
  );
}
// SolChat — the in-page Beacon chat section. It reads and writes the shared chat
// session (see BeaconChat.jsx) so the floating launcher and the full-screen
// overlay share the exact same history. An expand control opens full screen.
function SolChat() {
  const c = useBeaconChat();
  const e = c.estimate;
  const threadRef = React.useRef(null);

  React.useEffect(() => {
    const t = threadRef.current;
    if (t) t.scrollTop = t.scrollHeight;
  }, [c.messages, c.thinking, c.frame]);

  return (
    <section id="request" className="section pr-sec" style={{ position: "relative", overflow: "hidden" }}>
      <div className="haze-bloom" style={{ opacity: 0.2 }} aria-hidden="true" />
      <div className="wrap" style={{ position: "relative", zIndex: 2 }}>
        <div className="pr-chat" id="sol-chat" data-hook="sol-chat">
          <div className="pr-request-head">
            <div className="eyebrow"><span className="dot" />Start here</div>
            <h3 className="h-section" style={{ fontSize: 38, marginTop: 14 }}>Send your site. See a homepage prototype in 24 hours.</h3>
            <p className="p-lead" style={{ maxWidth: 620 }}>Choose a starting scope or talk with Beacon. We&rsquo;ll review your business, your current site, and what visitors need to do next, then prepare a first homepage direction before the call.</p>
          </div>

          <div className="chat-shell">
            {/* LEFT — build context / selected-estimate handoff */}
            <aside className="chat-context" data-hook="estimate-handoff"
              data-payment={e ? e.plan : ""} data-pages={e ? e.pages : ""} data-landing={e ? e.landingCount : ""}
              data-setup={e ? e.setupFee : ""} data-due={e ? (e.plan === "annual" ? e.annualFY : e.setupFee) : ""}
              data-first-year={e ? (e.plan === "annual" ? e.annualFY : e.monthlyFY) : ""} data-savings={e ? e.annualSavings : ""}>
              <h4 className="ctx-title">What we know so far</h4>
              <p className="ctx-sub">Beacon uses your selected scope, page count, and payment path to keep the conversation focused.</p>

              <div className={"ctx-estimate" + (e ? " is-set" : "")} data-hook="estimate-summary">
                {e ? (
                  <ul className="ctx-lines">
                    <li>Scope: {e.pagesLabel}{e.landingCount ? "" : ", no dedicated landing pages"}, {e.plan === "annual" ? "annual upfront payment with first-year Site Care included" : "monthly Site Care after launch"}.</li>
                    <li>Website build estimate: <b>{PR_USD(e.setupFee)}</b></li>
                    {e.plan === "annual" && <li>Effective build cost after savings: <b>{PR_USD(e.siteAfterSavings)}</b></li>}
                    <li>Due upfront: <b>{PR_USD(e.plan === "annual" ? e.annualFY : e.setupFee)}</b></li>
                    <li>Monthly Site Care: <b>{e.plan === "annual" ? "Included for the first year" : "$199/mo after launch"}</b></li>
                    <li>First-year total: <b>{PR_USD(e.plan === "annual" ? e.annualFY : e.monthlyFY)}</b></li>
                    {e.plan === "annual" && <li>Upfront payment savings: <b>{PR_USD(e.annualSavings)}</b></li>}
                    <li>Add-ons: <b>{e.landingCost ? PR_USD(e.landingCost) : "$0"}</b></li>
                    <li>Payment preference: <b>{e.plan === "annual" ? "Annual upfront" : "Monthly"}</b></li>
                  </ul>
                ) : (
                  "No estimate yet? No problem. Start with Beacon and we\u2019ll help you find the right starting point."
                )}
              </div>

              <div className="ctx-eyebrow ctx-eyebrow--steps">How the chat works</div>
              <ol className="ctx-steps">
                <li><span className="ctx-num">1</span><span>Share your site.</span></li>
                <li><span className="ctx-num">2</span><span>Answer a few questions.</span></li>
                <li><span className="ctx-num">3</span><span>Get your prototype.</span></li>
              </ol>
            </aside>

            {/* RIGHT — Sol chat */}
            <div className="chat-main" data-hook="chat-panel">
              <div className="chat-head">
                <div className="chat-head-id">
                  <span className="beacon-av beacon-av--head" aria-hidden="true"><img src="assets/beacon-face.png" alt="Beacon" /></span>
                  <div className="chat-head-text">
                    <h4 className="chat-title">Talk with Beacon</h4>
                    <p className="chat-subtitle">Share your site and get pointed in the right direction.</p>
                  </div>
                </div>
                <div className="chat-head-ctl">
                  <button type="button" className="chat-expand" aria-label="Open full screen" onClick={c.openFullscreen}><i className="ri-fullscreen-line" /></button>
                  <span className="pay-badge pay-badge--violet" style={{ flexShrink: 0 }}><span className="pay-badge-dot" />{c.leadStatusLabel}</span>
                </div>
              </div>

              <div className="chat-thread" id="chat-thread" data-hook="chat-thread" ref={threadRef}>
                <BeaconMessages />
              </div>

              {c.chatStatus && <p className="chat-status">{c.chatStatus}</p>}
              <BeaconComposer onSend={c.send} />
              {e && <p className="chat-foot-note" data-hook="estimate-attached-note">Estimate attached. The next replies will use this pricing context.</p>}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Pricing, SolChat });
