// schedule.jsx — Schedule a Call page + Call Confirmed page.
// Both pages embed Calendly. The schedule page uses an inline embed of the
// booking flow; the confirmed page is the post-booking landing surface that
// Calendly redirects back to once a slot is reserved.

const CALENDLY_INLINE_URL =
  "https://calendly.com/99-social-demo-call/99-social-demo-call?hide_gdpr_banner=1&primary_color=ff9900";

// Small inline gift icon — used by the "show up = bonus" callout.
function GiftIcon({ size = 18, color = "currentColor" }) {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  return (
    <svg {...p}>
      <path d="M20 12v9H4v-9" />
      <rect x="2" y="7" width="20" height="5" />
      <path d="M12 22V7" />
      <path d="M12 7H7.5a2.5 2.5 0 1 1 0-5C11 2 12 7 12 7z" />
      <path d="M12 7h4.5a2.5 2.5 0 1 0 0-5C13 2 12 7 12 7z" />
    </svg>
  );
}

// ── Show-up bonus callout ───────────────────────────────────────────────
// Two flavors: "preview" (before booking, on /schedule-a-call) and
// "confirmed" (after booking, on /call-confirmed). Same visual language,
// different copy that fits the moment.
function BonusCallout({ variant = "preview", compact = false }) {
  const copy = variant === "confirmed"
    ? {
        eyebrow: "Show-up bonus · live on the call",
        title: ["Show up to your call and ", { em: "unlock a special offer." }],
        body: "Our way of saying thanks for actually getting on the call with us. The bonus is only revealed live, and it's only available during the call itself — so add it to your calendar and join from a computer when the time comes.",
        chip: "Live-on-the-call only",
      }
    : {
        eyebrow: "Show-up bonus",
        title: ["Show up and ", { em: "unlock a special offer." }],
        body: compact
          ? "Get on the Google Meet at your booked time and our sales team will share a bonus offer not available anywhere else."
          : "Get on the Google Meet at your booked time and our sales team will share a bonus offer that's not available anywhere else on the site. Our way of saying thanks for actually showing up.",
        chip: "Revealed live, on the call",
      };

  return (
    <div className={"bonus-callout" + (compact ? " bonus-callout--compact" : "")}>
      <div className="bonus-callout-ribbon" aria-hidden="true">
        <GiftIcon size={compact ? 22 : 26} color="#fff" />
      </div>
      <div className="bonus-callout-body">
        <div className="bonus-callout-eyebrow">
          <span className="bonus-callout-dot" /> {copy.eyebrow}
        </div>
        <div className="bonus-callout-title">
          {copy.title.map((c, i) => typeof c === "string"
            ? <React.Fragment key={i}>{c}</React.Fragment>
            : <em key={i}>{c.em}</em>)}
        </div>
        <p className="bonus-callout-text">{copy.body}</p>
      </div>
      {!compact && (
        <div className="bonus-callout-chip">
          <span /> {copy.chip}
        </div>
      )}
    </div>
  );
}

// ── Reusable Calendly inline embed ──────────────────────────────────────
function CalendlyInline({ height = 720, url }) {
  const ref = React.useRef(null);
  const inited = React.useRef(false);

  React.useEffect(() => {
    if (inited.current || !ref.current) return;
    const tryInit = () => {
      if (window.Calendly && typeof window.Calendly.initInlineWidget === "function" && ref.current) {
        // Clear any previous mounted widget (e.g. SPA re-mount).
        ref.current.innerHTML = "";
        window.Calendly.initInlineWidget({
          url: url || CALENDLY_INLINE_URL,
          parentElement: ref.current,
          prefill: {},
          utm: {},
        });
        inited.current = true;
        return true;
      }
      return false;
    };
    if (tryInit()) return;
    // Poll briefly for the async widget script.
    const id = setInterval(() => { if (tryInit()) clearInterval(id); }, 200);
    return () => clearInterval(id);
  }, [url]);

  return (
    <div
      ref={ref}
      className="calendly-inline-widget"
      style={{ minWidth: 320, width: "100%", height, background: "var(--bg)" }}
    />
  );
}

// ── Trust row used on both pages ────────────────────────────────────────
function ScheduleTrustRow() {
  return (
    <div className="sch-trust">
      <div className="sch-trust-item">
        <span className="sch-trust-icon"><Icon name="clock" size={14} /></span>
        <div>
          <b>20 minutes</b>
          <span>No-pressure conversation</span>
        </div>
      </div>
      <span className="sch-trust-sep" />
      <div className="sch-trust-item">
        <span className="sch-trust-icon"><Icon name="user" size={14} /></span>
        <div>
          <b>Real human</b>
          <span>Our sales team — not a bot</span>
        </div>
      </div>
      <span className="sch-trust-sep" />
      <div className="sch-trust-item">
        <span className="sch-trust-icon"><Icon name="video" size={14} /></span>
        <div>
          <b>Google Meet</b>
          <span>Link sent to your inbox</span>
        </div>
      </div>
      <span className="sch-trust-sep" />
      <div className="sch-trust-item">
        <span className="sch-trust-icon"><Icon name="dollar" size={14} /></span>
        <div>
          <b>Free</b>
          <span>No card, no commitment</span>
        </div>
      </div>
    </div>
  );
}

// ── What we'll cover on the call ────────────────────────────────────────
const SCH_AGENDA = [
  { icon: "user",     title: "About your business",       body: "Industry, audience, what you sell, and what you're trying to grow. The faster we understand it, the better we can help." },
  { icon: "image",    title: "Sample posts in your niche", body: "We'll pull up real client work in your space so you can see exactly how the content will look on your accounts." },
  { icon: "calendar", title: "How posting actually works", body: "Onboarding, approvals, scheduling, and what your first month with us looks like — start to finish." },
  { icon: "dollar",   title: "Pricing for your situation", body: "Plans start at $99/mo. We'll help you pick the right number of posts and channels for your goals — no upsell theater." },
];

// ── Schedule a Call page ────────────────────────────────────────────────
function SchedulePage({ onOpenModal, onBookDemo, onNav }) {
  // Show all FAQs, surfacing the most booking-relevant ones first so the
  // collapsed view still feels purposeful before the user expands the rest.
  const bookingFaqs = React.useMemo(() => {
    const priority = [
      "What happens after I sign up?",
      "How does pricing actually work?",
      "Do real humans write my content, or is it AI?",
      "Will I see the posts before they go live?",
      "Which platforms are supported?",
      "What is your cancellation policy?",
      "What is your refund policy?",
      "What if I have more questions?",
    ];
    const head = priority
      .map((q) => FAQS.find((f) => f.q === q))
      .filter(Boolean);
    const headSet = new Set(head.map((f) => f.q));
    const tail = FAQS.filter((f) => !headSet.has(f.q));
    return [...head, ...tail];
  }, []);

  const [openFaq, setOpenFaq] = React.useState(0);
  const [showAllBookingFaqs, setShowAllBookingFaqs] = React.useState(false);
  const BOOKING_FAQ_INITIAL = 6;
  const visibleBookingFaqs = showAllBookingFaqs
    ? bookingFaqs
    : bookingFaqs.slice(0, BOOKING_FAQ_INITIAL);

  return (
    <div className="page">
      {/* Compact hero — kicker + headline only, so the Calendly comes up the page */}
      <section className="hero sch-hero sch-hero--compact">
        <div className="container">
          <div style={{ maxWidth: 860, margin: "0 auto", textAlign: "center" }}>
            <span className="kicker" style={{ marginBottom: 18 }}><span className="dot" /> Book a 20-minute call</span>
            <h1>Talk to our sales team. <span className="display-em">Decide if we're a fit.</span></h1>
          </div>
        </div>
      </section>

      {/* Calendly + sidebar (bonus + what we'll cover + quote) */}
      <section className="section section--tight sch-cal-section">
        <div className="container">
          <div className="sch-grid">
            <div className="sch-cal">
              <div className="sch-cal-head">
                <Icon name="calendar" size={16} color="var(--primary)" />
                <span>Pick a time that works for you</span>
              </div>
              <CalendlyInline height={760} />
            </div>

            <aside className="sch-aside">
              <BonusCallout variant="preview" compact={true} />

              <div className="sch-aside-section">
                <div className="kicker"><span className="dot" /> What we'll cover</div>
                <ul className="sch-agenda sch-agenda--tight">
                  {SCH_AGENDA.map((it) => (
                    <li key={it.title}>
                      <span className="sch-agenda-icon"><Icon name={it.icon} size={14} /></span>
                      <div>
                        <b>{it.title}</b>
                      </div>
                    </li>
                  ))}
                </ul>
              </div>

              <div className="sch-aside-quote">
                <div className="stars" style={{ color: "var(--primary)", marginBottom: 8 }}>
                  {Array.from({ length: 5 }, (_, k) => <Icon key={k} name="star" size={13} />)}
                </div>
                <p>"The call was actually useful. They showed me posts they'd made for other coffee shops and explained exactly what my first month would look like. No pressure, no upsell."</p>
                <div className="sch-aside-quote-foot">
                  <div className="testi-avatar" style={{ background: "oklch(0.7 0.17 30)", width: 32, height: 32, fontSize: 12 }}>MV</div>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>Maya Vance</div>
                    <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Hilltop Coffee Roasters · Austin TX</div>
                  </div>
                </div>
              </div>
            </aside>
          </div>

          {/* Trust row moved below the calendar so the calendar lands higher */}
          <div style={{ marginTop: 36 }}>
            <ScheduleTrustRow />
          </div>
        </div>
      </section>

      {/* Trust strip — proof block */}
      <TrustStrip />

      {/* Sample posts to show client work */}
      <section className="section section--tight section--bg2">
        <div className="container">
          <div className="section-head">
            <div className="kicker"><span className="dot" /> Real client work</div>
            <h2>The kind of posts <span className="display-em">we'll show you on the call.</span></h2>
            <p>A look at recent posts created for actual clients across industries. We'll pull up the most relevant ones to your business once we hop on.</p>
          </div>
          <div className="ex-grid">
            {EXAMPLE_POSTS.filter((p) => p.featured).slice(0, 6).map((p, i) => (
              <ExamplePost key={i} post={p} />
            ))}
          </div>
          <div style={{ display: "flex", justifyContent: "center", marginTop: 32 }}>
            <button className="btn btn--ghost btn--lg" onClick={() => onNav("examples")}>
              See more examples <Icon name="arrow-right" size={14} />
            </button>
          </div>
        </div>
      </section>

      {/* Testimonials */}
      <Testimonials short={true} tone="bg" />

      {/* FAQ — focused subset */}
      <section className="section section--bg2">
        <div className="container">
          <div className="section-head">
            <div className="kicker"><span className="dot" /> Before the call</div>
            <h2>Questions people ask <span className="display-em">before booking.</span></h2>
            <p>If yours isn't here, just ask on the call — that's what it's for.</p>
          </div>
          <div style={{ maxWidth: 820, margin: "0 auto" }}>
            <div className="faq-list">
              {visibleBookingFaqs.map((f, i) => (
                <div key={i} className="faq-item" data-open={openFaq === i ? "1" : "0"}>
                  <button className="faq-q" onClick={() => setOpenFaq(openFaq === i ? -1 : i)}>
                    <span>{f.q}</span>
                    <span className="faq-toggle"><Icon name="plus" size={14} /></span>
                  </button>
                  <div className="faq-a">{f.a}</div>
                </div>
              ))}
            </div>
            {bookingFaqs.length > BOOKING_FAQ_INITIAL && (
              <div style={{ display: "flex", justifyContent: "center", marginTop: 32 }}>
                <button
                  className="btn btn--ghost btn--lg"
                  onClick={() => {
                    setShowAllBookingFaqs(!showAllBookingFaqs);
                    if (showAllBookingFaqs) setOpenFaq(-1);
                  }}
                >
                  {showAllBookingFaqs
                    ? "Show fewer questions"
                    : `Show all ${bookingFaqs.length} questions`}
                  <Icon name={showAllBookingFaqs ? "arrow-left" : "arrow-right"} size={14} />
                </button>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Guarantee */}
      <Guarantee tone="bg" onOpenModal={onOpenModal} />

      {/* Final CTA — book/sign up */}
      <FinalCTA onOpenModal={onOpenModal} onBookDemo={onBookDemo} />
    </div>
  );
}

// ── Call Confirmed page ────────────────────────────────────────────────
// Calendly redirects here after a successful booking. Mirrors the structure
// of the screenshot the team shared, then layers in the homepage video,
// FAQ subset, and "how to make the most of your call" guidance.
function CallConfirmedPage({ onOpenModal, onBookDemo, onNav }) {
  const prepFaqs = React.useMemo(() => {
    const priority = [
      "What happens after I sign up?",
      "How does pricing actually work?",
      "Do real humans write my content, or is it AI?",
      "How will you know what to post for my company?",
      "Which platforms are supported?",
      "What is your cancellation policy?",
    ];
    const head = priority
      .map((q) => FAQS.find((f) => f.q === q))
      .filter(Boolean);
    const headSet = new Set(head.map((f) => f.q));
    const tail = FAQS.filter((f) => !headSet.has(f.q));
    return [...head, ...tail];
  }, []);

  const [openFaq, setOpenFaq] = React.useState(0);
  const [showAllPrepFaqs, setShowAllPrepFaqs] = React.useState(false);
  const PREP_FAQ_INITIAL = 6;
  const visiblePrepFaqs = showAllPrepFaqs
    ? prepFaqs
    : prepFaqs.slice(0, PREP_FAQ_INITIAL);

  return (
    <div className="page">
      {/* Confirmation hero */}
      <section className="hero confirm-hero" style={{ paddingBottom: 32 }}>
        <div className="container">
          <div style={{ maxWidth: 880, margin: "0 auto", textAlign: "center" }}>
            <div className="confirm-check" aria-hidden="true">
              <Icon name="check" size={36} color="#fff" />
            </div>
            <h1 style={{ marginTop: 16 }}>Your call is <span className="display-em">confirmed!</span></h1>
            <p className="hero-lede" style={{ margin: "16px auto 0", maxWidth: 620 }}>
              Thanks for booking a call with us. We're looking forward to it.
            </p>
            <div className="confirm-note">
              <strong>NOTE:</strong>{" "}
              <span>
                Please take a moment to <mark>watch the video below</mark> to make the most out of your demo call!
              </span>
              <div className="confirm-note-sub">
                It will answer many questions for you ahead of time so the sales team can focus on how we can best help you.
              </div>
            </div>
          </div>
          <div style={{ maxWidth: 880, margin: "28px auto 0" }}>
            <BonusCallout variant="confirmed" />
          </div>
        </div>
      </section>

      {/* Three-step prep checklist (mirrors the screenshot) */}
      <section className="section section--tight">
        <div className="container">
          <div className="confirm-steps">
            <div className="confirm-step">
              <span className="confirm-step-bullet"><Icon name="check" size={16} color="#fff" /></span>
              <div>
                <b>Click 'Yes' in the email calendar invite</b>
                <p>Based on your settings, the event may not show in your calendar until you respond 'Yes' to the event email confirmation.</p>
                <div className="confirm-calmock">
                  <div className="confirm-calmock-icon">
                    <div className="confirm-calmock-icon-top" />
                    <div className="confirm-calmock-icon-body">
                      <span /><span /><span />
                    </div>
                  </div>
                  <div className="confirm-calmock-body">
                    <div className="confirm-calmock-title">99DollarSocial Demo Confirmed</div>
                    <div className="confirm-calmock-link">View on Google Calendar</div>
                    <div className="confirm-calmock-meta">
                      <div><span>When</span><i className="confirm-calmock-redact" style={{ width: 180 }} /></div>
                      <div><span>Where</span><b>Google Meet (instructions in description)</b></div>
                      <div><span>Who</span><i className="confirm-calmock-redact" style={{ width: 120 }} /></div>
                    </div>
                    <div className="confirm-calmock-actions">
                      <span className="confirm-calmock-arrow" aria-hidden="true">→</span>
                      <button className="confirm-calmock-btn confirm-calmock-btn--yes">
                        Yes <span className="confirm-calmock-caret">▾</span>
                      </button>
                      <button className="confirm-calmock-btn">Maybe</button>
                      <button className="confirm-calmock-btn">No</button>
                      <span className="confirm-calmock-more">More options</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="confirm-step">
              <span className="confirm-step-bullet"><Icon name="check" size={16} color="#fff" /></span>
              <div>
                <b>The call will be on Google Meet:</b>
                <p>You will receive further information on your email and a link to join the call. It's best to join from a computer or desktop (not a phone) so we can share a presentation with you.</p>
              </div>
            </div>

            <div className="confirm-step">
              <span className="confirm-step-bullet"><Icon name="check" size={16} color="#fff" /></span>
              <div>
                <b>The call usually takes 10-20 minutes:</b>
                <p>We will be learning more about your business and needs to see if we can help — and then us telling you a lot more about how $99 Social works and what you can expect from working with us.</p>
              </div>
            </div>

            <div className="confirm-step">
              <span className="confirm-step-bullet"><Icon name="check" size={16} color="#fff" /></span>
              <div>
                <b>Have your goals + questions ready:</b>
                <p>Jot down what you want from social media (more leads? more visibility? consistency?) and the one or two questions you really want answered. We'll make sure they get covered.</p>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* The homepage demo video */}
      <div id="watch-video">
        <VideoSection tone="bg-2" />
      </div>

      {/* Sample client work — gives them something to react to on the call */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div className="kicker"><span className="dot" /> Real client work</div>
            <h2>Get a feel for <span className="display-em">what we make.</span></h2>
            <p>A quick scroll through recent posts created for actual clients across industries. We'll pull up the most relevant ones for your business on the call.</p>
          </div>
          <div className="ex-grid">
            {EXAMPLE_POSTS.filter((p) => p.featured).slice(0, 6).map((p, i) => (
              <ExamplePost key={i} post={p} />
            ))}
          </div>
          <div style={{ display: "flex", justifyContent: "center", marginTop: 32 }}>
            <button className="btn btn--ghost btn--lg" onClick={() => onNav("examples")}>
              See all our work <Icon name="arrow-right" size={14} />
            </button>
          </div>
        </div>
      </section>

      {/* Trust strip */}
      <TrustStrip />

      {/* Testimonials */}
      <Testimonials short={true} tone="bg-2" />

      {/* FAQ — pre-call subset */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div className="kicker"><span className="dot" /> Before we talk</div>
            <h2>Common questions <span className="display-em">we'll cover on the call.</span></h2>
            <p>Skim these so we can spend the call on what matters most to your business.</p>
          </div>
          <div style={{ maxWidth: 820, margin: "0 auto" }}>
            <div className="faq-list">
              {visiblePrepFaqs.map((f, i) => (
                <div key={i} className="faq-item" data-open={openFaq === i ? "1" : "0"}>
                  <button className="faq-q" onClick={() => setOpenFaq(openFaq === i ? -1 : i)}>
                    <span>{f.q}</span>
                    <span className="faq-toggle"><Icon name="plus" size={14} /></span>
                  </button>
                  <div className="faq-a">{f.a}</div>
                </div>
              ))}
            </div>
            {prepFaqs.length > PREP_FAQ_INITIAL && (
              <div style={{ display: "flex", justifyContent: "center", marginTop: 32 }}>
                <button
                  className="btn btn--ghost btn--lg"
                  onClick={() => {
                    setShowAllPrepFaqs(!showAllPrepFaqs);
                    if (showAllPrepFaqs) setOpenFaq(-1);
                  }}
                >
                  {showAllPrepFaqs
                    ? "Show fewer questions"
                    : `Show all ${prepFaqs.length} questions`}
                  <Icon name={showAllPrepFaqs ? "arrow-left" : "arrow-right"} size={14} />
                </button>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Reschedule / cancel helper */}
      <section className="section section--tight section--bg2">
        <div className="container">
          <div className="confirm-helper">
            <div>
              <div className="kicker"><span className="dot" /> Need to make a change?</div>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 26, letterSpacing: "-0.02em", margin: "10px 0 8px" }}>
                Reschedule or cancel <span className="display-em">anytime.</span>
              </h3>
              <p style={{ color: "var(--ink-2)" }}>
                Use the reschedule / cancel links inside the calendar invite Calendly emailed you. Or pick a new time below and we'll move it for you.
              </p>
            </div>
            <div className="confirm-helper-actions">
              <button className="btn btn--primary" onClick={onBookDemo}>
                <Icon name="calendar" size={14} /> Pick a new time
              </button>
              <a href="mailto:hello@99social.com" className="btn btn--ghost">
                <Icon name="mail" size={14} /> Email us
              </a>
            </div>
          </div>
        </div>
      </section>

      <FinalCTA onOpenModal={onOpenModal} onBookDemo={onBookDemo} />
    </div>
  );
}

Object.assign(window, {
  CalendlyInline,
  SchedulePage,
  CallConfirmedPage,
});
