// Public landing page — branded marketing front door with feature highlights,
// pricing packages, and an integrated sign-up / log-in / purchase flow.
// Rendered (instead of the bare LoginPage) whenever auth is in password mode
// and no user is signed in.

const LP_PLATFORMS = ["facebook", "instagram", "x", "youtube", "tiktok", "linkedin"];

const LP_FEATURES = [
  {
    icon: "Grid",
    title: "Every brand in one place",
    body: "Run Beam & Bloom, Church Grid, and any client side-by-side. Switch businesses in one tap — separate calendars, voices, and reports, zero re-logins.",
  },
  {
    icon: "Sparkles",
    title: "AI content studio",
    body: "Generate captions, on-brand images, and realistic marketing video right in the composer. Tracks token spend so you never blow the marketing budget.",
  },
  {
    icon: "Calendar",
    title: "Plan & schedule visually",
    body: "Drag-and-drop calendar, best-time recommendations, and one post tailored natively to every platform in a single pass.",
  },
  {
    icon: "Check",
    title: "Approvals without the friction",
    body: "Send a free magic-link review to clients — no account, no login. They approve, reject, or request changes from their phone.",
  },
  {
    icon: "Inbox",
    title: "Engage everywhere",
    body: "A unified inbox for comments and DMs, social listening, and Google/Yelp/Facebook review management — all in one feed.",
  },
  {
    icon: "Bar",
    title: "Know what actually works",
    body: "Fast analytics, A/B testing across channels, competitor benchmarks, and white-label reports you can schedule and send automatically.",
  },
  {
    icon: "Plug",
    title: "Never miss a post",
    body: "Connection-health alerts, a pre-publish validator, automatic retries, and delivery receipts. If something's wrong, you hear it before your audience does.",
  },
  {
    icon: "Heart",
    title: "Honest, flat pricing",
    body: "Priced per business, not per seat. Unlimited free teammates, no surprise overage bills, cancel anytime. The trust other tools forgot.",
  },
];

const LP_PLAN_FEATURES = {
  free: ["1 business", "3 social channels", "Visual calendar & scheduling", "Basic analytics", "Community support"],
  starter: ["1 business", "All social channels", "Approvals & free client review links", "Full analytics dashboard", "Unlimited free team seats", "Email support"],
  growth: ["3 businesses", "Everything in Starter", "AI studio — text, image & video", "A/B testing & automation", "Scheduled white-label reports", "Priority support"],
  scale: ["Unlimited businesses", "Everything in Growth", "Agency tools & white-label portal", "Listening & review management", "Public API & webhooks", "Dedicated success manager"],
};

const LP_FALLBACK_PLANS = [
  { id: "free", name: "Free", price: 0, blurb: "1 business, 3 channels, basic scheduling" },
  { id: "starter", name: "Starter", price: 19, blurb: "All channels, approvals, analytics, unlimited free seats" },
  { id: "growth", name: "Growth", price: 39, blurb: "Everything in Starter + AI suite, reports, automation", popular: true },
  { id: "scale", name: "Scale", price: 79, blurb: "Everything in Growth + agency tools, white-label, priority support" },
];

function GoogleGlyph() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.76h3.56c2.08-1.92 3.28-4.74 3.28-8.09z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.56-2.76c-.98.66-2.23 1.06-3.72 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z"/>
      <path fill="#FBBC05" d="M5.84 14.11c-.22-.66-.35-1.36-.35-2.11s.13-1.45.35-2.11V7.05H2.18A11 11 0 0 0 1 12c0 1.77.42 3.45 1.18 4.95l3.66-2.84z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.05l3.66 2.84C6.71 7.29 9.14 5.38 12 5.38z"/>
    </svg>
  );
}

function LandingAuthModal({ open, mode, setMode, plan, plans, onClose, notice }) {
  const hub = useClearCast();
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [name, setName] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");
  const chosen = plans.find((p) => p.id === plan);
  const signupsOpen = !!(hub.data && hub.data.signupsOpen);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (open) window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const submit = async (e) => {
    if (e) e.preventDefault();
    setError("");
    setBusy(true);
    try {
      if (mode === "login") {
        await hub.actions.login(email.trim(), password);
      } else {
        await hub.actions.signup({ email: email.trim(), password, name: name.trim() });
        if (plan && plan !== "free") {
          try { await hub.actions.changePlan(plan); } catch (err) { /* plan can be set later in Billing */ }
        }
      }
      // On success the app re-renders past the auth wall and this modal unmounts.
    } catch (err) {
      setError(err.message || "Something went wrong — please try again.");
      setBusy(false);
    }
  };

  return (
    <div className="lp-modal-overlay" onClick={onClose}>
      <form className="lp-modal" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
        <button type="button" className="lp-modal-close" onClick={onClose} aria-label="Close"><Icon.X width="18" height="18" /></button>
        <div className="lp-modal-brand">
          <div className="brand-mark" style={{ width: 40, height: 40, borderRadius: 11 }}>CC</div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 17 }}>{mode === "login" ? "Welcome back" : "Create your account"}</div>
            <div className="muted" style={{ fontSize: 12.5 }}>
              {mode === "login" ? "Sign in to your ClearCast workspace" : chosen && chosen.id !== "free" ? `Starting on the ${chosen.name} plan · $${chosen.price}/mo per business` : "Free to start — no credit card required"}
            </div>
          </div>
        </div>

        {notice && <div className="lp-auth-notice">{notice}</div>}

        <button type="button" className="lp-google-btn" onClick={() => { window.location.href = "/api/auth/google"; }}>
          <GoogleGlyph /> Continue with Google
        </button>
        <div className="lp-or"><span>or</span></div>

        {mode === "signup" && (
          <label className="lp-field">
            <span>Your name</span>
            <input className="input" placeholder="Jane Maker" value={name} onChange={(e) => setName(e.target.value)} autoFocus />
          </label>
        )}
        <label className="lp-field">
          <span>Work email</span>
          <input className="input" type="email" placeholder="you@business.com" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus={mode === "login"} />
        </label>
        <label className="lp-field">
          <span>Password</span>
          <input className="input" type="password" placeholder={mode === "signup" ? "Create a password" : "Your password"} value={password} onChange={(e) => setPassword(e.target.value)} />
        </label>

        {error && <div className="lp-modal-error">{error}</div>}

        <button type="submit" className="btn btn-primary lp-modal-submit" disabled={busy || !email || !password || (mode === "signup" && !name)}>
          {busy ? "Please wait…" : mode === "login" ? "Sign in" : chosen && chosen.id !== "free" ? `Start with ${chosen.name}` : "Create free account"}
        </button>

        {mode === "signup" && (
          <div className="lp-modal-trust">
            <span><Icon.Check width="13" height="13" /> Cancel anytime</span>
            <span><Icon.Check width="13" height="13" /> Unlimited free seats</span>
            <span><Icon.Check width="13" height="13" /> No surprise bills</span>
          </div>
        )}

        <div className="lp-modal-switch muted">
          {!signupsOpen
            ? (mode === "login" ? "Invite-only during early access." : <>Already have an account? <button type="button" onClick={() => { setMode("login"); setError(""); }}>Sign in</button></>)
            : <>{mode === "login" ? "New to ClearCast? " : "Already have an account? "}<button type="button" onClick={() => { setMode(mode === "login" ? "signup" : "login"); setError(""); }}>{mode === "login" ? "Create an account" : "Sign in"}</button></>}
        </div>
      </form>
    </div>
  );
}

function LandingPage() {
  const hub = useClearCast();
  const data = (hub && hub.data) || {};
  const plans = (Array.isArray(data.billingPlans) && data.billingPlans.length ? data.billingPlans : LP_FALLBACK_PLANS);
  const [authOpen, setAuthOpen] = React.useState(false);
  const [authMode, setAuthMode] = React.useState("signup");
  const [selectedPlan, setSelectedPlan] = React.useState("growth");
  const [authNotice, setAuthNotice] = React.useState("");

  // Returning from /api/auth/google with a status flag (?auth=...) — surface a
  // friendly message and open the sign-in modal.
  React.useEffect(() => {
    let flag = "";
    try { flag = new URLSearchParams(window.location.search).get("auth") || ""; } catch (e) { flag = ""; }
    if (!flag) return;
    const messages = {
      "google-setup": "Google sign-in isn't switched on yet — email sign-up works now, and Google will light up the moment it's enabled in Supabase.",
      "google-error": "Google sign-in hit a snag. Please try again, or use your email below.",
      "unavailable": "Sign-in isn't fully configured yet — please use email for now."
    };
    setAuthNotice(messages[flag] || "");
    setAuthMode("login");
    setAuthOpen(true);
    try { window.history.replaceState({}, "", window.location.pathname); } catch (e) { /* ignore */ }
  }, []);

  const signupsOpen = !!(data && data.signupsOpen);
  const openAuth = (mode, plan) => {
    setAuthNotice("");
    if (mode === "signup" && !signupsOpen) {
      setAuthMode("login");
      setAuthNotice("ClearCast is invite-only during early access — please sign in, or ask an admin to set up your account.");
    } else {
      setAuthMode(mode);
    }
    if (plan) setSelectedPlan(plan);
    setAuthOpen(true);
  };
  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <div className="lp">
      {/* Nav */}
      <header className="lp-nav">
        <div className="lp-nav-inner">
          <div className="lp-logo">
            <div className="brand-mark" style={{ width: 34, height: 34, borderRadius: 9 }}>CC</div>
            <span>ClearCast</span>
          </div>
          <nav className="lp-nav-links">
            <button onClick={() => scrollTo("features")}>Features</button>
            <button onClick={() => scrollTo("pricing")}>Pricing</button>
            <button onClick={() => scrollTo("why")}>Why ClearCast</button>
          </nav>
          <div className="lp-nav-cta">
            {typeof ThemeToggle === "function" && <ThemeToggle />}
            <button className="btn btn-ghost" onClick={() => openAuth("login")}>Log in</button>
            <button className="btn btn-primary" onClick={() => openAuth("signup", "growth")}>Get started free</button>
          </div>
        </div>
      </header>

      {/* Hero */}
      <section className="lp-hero">
        <div className="lp-hero-inner">
          <div className="lp-eyebrow"><Icon.Sparkles width="13" height="13" /> The all-in-one social marketing suite</div>
          <h1>Market every brand you run<br /><em>without the chaos.</em></h1>
          <p className="lp-hero-sub">
            ClearCast brings scheduling, AI content, approvals, engagement, and analytics for all your businesses into one radically simple command center — powerful enough for pros, simple enough for day one.
          </p>
          <div className="lp-hero-cta">
            <button className="btn btn-primary btn-lg" onClick={() => openAuth("signup", "growth")}>Start free — no card needed</button>
            <button className="btn btn-ghost btn-lg" onClick={() => scrollTo("pricing")}>See pricing</button>
          </div>
          <div className="lp-platforms">
            <span className="muted">Publishes to</span>
            {LP_PLATFORMS.map((p) => <PlatformIcon key={p} id={p} size={26} />)}
          </div>
        </div>
        <div className="lp-hero-visual" aria-hidden="true">
          <div className="lp-mock">
            <div className="lp-mock-top">
              <div className="brand-mark" style={{ width: 24, height: 24, borderRadius: 7, fontSize: 11 }}>CC</div>
              <span className="lp-mock-biz">Beam &amp; Bloom</span>
              <span className="lp-mock-pill">3 scheduled today</span>
            </div>
            <div className="lp-mock-row">
              <div className="lp-mock-day">Mon</div>
              <div className="lp-mock-card a"><b>Spring engraving sale</b><small>9:00 AM · IG · FB</small></div>
            </div>
            <div className="lp-mock-row">
              <div className="lp-mock-day">Tue</div>
              <div className="lp-mock-card b"><b>Customer spotlight reel</b><small>12:30 PM · TikTok · YT</small></div>
            </div>
            <div className="lp-mock-row">
              <div className="lp-mock-day">Wed</div>
              <div className="lp-mock-card c"><span className="lp-mock-ai"><Icon.Sparkles width="11" height="11" /> AI draft</span><b>Sunday service invite</b><small>Awaiting approval</small></div>
            </div>
            <div className="lp-mock-foot">
              <span><Icon.TrendUp width="13" height="13" /> Reach +24%</span>
              <span><Icon.Check width="13" height="13" /> All channels healthy</span>
            </div>
          </div>
        </div>
      </section>

      <div className="lp-proof">
        Built to run real businesses — <b>Beam &amp; Bloom</b> laser engraving and <b>Church Grid</b> — and ready for yours.
      </div>

      {/* Features */}
      <section className="lp-section" id="features">
        <div className="lp-section-head">
          <div className="lp-eyebrow">Everything, in one app</div>
          <h2>One suite that replaces your whole stack</h2>
          <p>Stop paying for five tools that don't talk to each other. ClearCast does the work of Hootsuite, Buffer, Later, and Sprout — minus the price and the headaches.</p>
        </div>
        <div className="lp-features">
          {LP_FEATURES.map((f) => {
            const Glyph = Icon[f.icon] || Icon.Check;
            return (
              <div className="lp-feature" key={f.title}>
                <div className="lp-feature-icon"><Glyph width="20" height="20" /></div>
                <h3>{f.title}</h3>
                <p>{f.body}</p>
              </div>
            );
          })}
        </div>
      </section>

      {/* Why / differentiators */}
      <section className="lp-section lp-why" id="why">
        <div className="lp-section-head">
          <div className="lp-eyebrow">Why teams switch</div>
          <h2>Built from real complaints about everyone else</h2>
        </div>
        <div className="lp-why-grid">
          <div className="lp-why-card">
            <div className="lp-why-x">Them</div>
            <p>Per-seat pricing that punishes you for adding a teammate.</p>
            <div className="lp-why-check"><Icon.Check width="15" height="15" /> ClearCast</div>
            <p className="lp-why-good">Flat price per business. Invite your whole team free.</p>
          </div>
          <div className="lp-why-card">
            <div className="lp-why-x">Them</div>
            <p>Posts silently fail and you find out from an angry client.</p>
            <div className="lp-why-check"><Icon.Check width="15" height="15" /> ClearCast</div>
            <p className="lp-why-good">Pre-publish checks, health alerts, auto-retry, delivery receipts.</p>
          </div>
          <div className="lp-why-card">
            <div className="lp-why-x">Them</div>
            <p>AI features locked behind a separate, pricey add-on.</p>
            <div className="lp-why-check"><Icon.Check width="15" height="15" /> ClearCast</div>
            <p className="lp-why-good">Text, image &amp; video AI built in — with budget tracking.</p>
          </div>
          <div className="lp-why-card">
            <div className="lp-why-x">Them</div>
            <p>Clients need logins and seats just to approve a post.</p>
            <div className="lp-why-check"><Icon.Check width="15" height="15" /> ClearCast</div>
            <p className="lp-why-good">Free magic-link approvals — they tap once, you're done.</p>
          </div>
        </div>
      </section>

      {/* Pricing */}
      <section className="lp-section lp-pricing-section" id="pricing">
        <div className="lp-section-head">
          <div className="lp-eyebrow">Simple pricing</div>
          <h2>Pick a plan. Add businesses, not surprises.</h2>
          <p>Every plan includes unlimited free teammates and our no-surprise-billing promise. Start free, upgrade when you're ready.</p>
        </div>
        <div className="lp-pricing">
          {plans.map((plan) => {
            const features = LP_PLAN_FEATURES[plan.id] || (plan.blurb ? plan.blurb.split(",").map((s) => s.trim()) : []);
            const popular = plan.popular || plan.id === "growth";
            return (
              <div className={`lp-plan ${popular ? "popular" : ""}`} key={plan.id}>
                {popular && <div className="lp-plan-badge">Most popular</div>}
                <div className="lp-plan-name">{plan.name}</div>
                <div className="lp-plan-price">
                  {plan.price === 0 ? <span className="lp-plan-amt">Free</span> : <><span className="lp-plan-amt">${plan.price}</span><span className="lp-plan-per">/mo<br />per business</span></>}
                </div>
                <button className={`btn ${popular ? "btn-primary" : "btn-ghost"} lp-plan-cta`} onClick={() => openAuth("signup", plan.id)}>
                  {plan.id === "free" ? "Start free" : `Choose ${plan.name}`}
                </button>
                <ul className="lp-plan-features">
                  {features.map((feat, i) => (
                    <li key={i}><Icon.Check width="14" height="14" /> {feat}</li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>
        <div className="lp-pricing-note muted">
          Prices are per business / month. Need to run an agency or many brands? <button className="lp-inline-link" onClick={() => openAuth("signup", "scale")}>Talk to us about Scale</button>.
        </div>
      </section>

      {/* Final CTA */}
      <section className="lp-cta-band">
        <h2>Your whole marketing operation, finally in one place.</h2>
        <p>Set up your first business and schedule a post in the next five minutes.</p>
        <div className="lp-hero-cta" style={{ justifyContent: "center" }}>
          <button className="btn btn-primary btn-lg" onClick={() => openAuth("signup", "growth")}>Get started free</button>
          <button className="btn btn-ghost btn-lg" onClick={() => openAuth("login")}>Log in</button>
        </div>
      </section>

      {/* Footer */}
      <footer className="lp-footer">
        <div className="lp-footer-inner">
          <div className="lp-logo">
            <div className="brand-mark" style={{ width: 30, height: 30, borderRadius: 8, fontSize: 13 }}>CC</div>
            <span>ClearCast</span>
          </div>
          <div className="lp-footer-links">
            <button onClick={() => scrollTo("features")}>Features</button>
            <button onClick={() => scrollTo("pricing")}>Pricing</button>
            <button onClick={() => openAuth("login")}>Log in</button>
            <button onClick={() => openAuth("signup", "growth")}>Get started</button>
          </div>
          <div className="lp-footer-copy muted">© 2026 ClearCast · The honest marketing command center</div>
        </div>
      </footer>

      <LandingAuthModal
        open={authOpen}
        mode={authMode}
        setMode={setAuthMode}
        plan={selectedPlan}
        plans={plans}
        notice={authNotice}
        onClose={() => setAuthOpen(false)}
      />
    </div>
  );
}

window.LandingPage = LandingPage;
