/* global React, useRoute, useToast, I */
const { useState: useDeskState } = React;

function DeskCheckoutBanner() {
  const params = new URLSearchParams(window.location.search);
  const status = params.get("checkout");
  if (status === "success") {
    return (
      <div className="desk-banner desk-banner-ok" role="status">
        Payment received. Check your email within 24 business hours for install scheduling and your deploy token.
      </div>
    );
  }
  if (status === "cancel") {
    return (
      <div className="desk-banner desk-banner-err" role="status">
        Checkout canceled. You can try again when ready.
      </div>
    );
  }
  return null;
}

function DeskPricingCard({ featured, title, price, suffix, features, children }) {
  return (
    <article
      className="desk-card"
      style={{ borderColor: featured ? "var(--gold)" : "var(--border)" }}
    >
      <div className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", color: "var(--text-3)", textTransform: "uppercase" }}>
        {title}
      </div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 32, fontWeight: 500, margin: "10px 0 14px", color: "var(--text-1)" }}>
        {price}
        {suffix ? (
          <span style={{ fontSize: 14, color: "var(--text-3)", fontWeight: 400, marginLeft: 6 }}>{suffix}</span>
        ) : null}
      </div>
      <ul className="desk-features">{features.map((f) => <li key={f}>{f}</li>)}</ul>
      {children}
    </article>
  );
}

function Desk() {
  const toast = useToast();
  const [agentCode, setAgentCode] = useDeskState("");
  const [loading, setLoading] = useDeskState(false);

  async function buyLifetime() {
    setLoading(true);
    try {
      const r = await fetch("/api/desk-checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ agentCode: agentCode.trim() || undefined }),
      });
      const data = await r.json();
      if (!r.ok || !data.url) throw new Error(data.detail || data.error || "Checkout unavailable");
      window.location.href = data.url;
    } catch (e) {
      toast(e.message || "Checkout failed. Email simeon@elevenviews.io.");
      setLoading(false);
    }
  }

  return (
    <main className="fade">
      <section className="container" style={{ paddingTop: 72, paddingBottom: 24 }}>
        <DeskCheckoutBanner />
        <span className="eyebrow eyebrow-gold">§ Eleven Views Desk</span>
        <h1 className="serif balance" style={{ fontSize: "clamp(40px, 6vw, 72px)", lineHeight: 0.98, letterSpacing: "-0.02em", margin: "16px 0 20px", maxWidth: 900 }}>
          Your operations team,<br />
          <em style={{ fontStyle: "italic", color: "var(--gold-soft)" }}>on your own server.</em>
        </h1>
        <p className="pretty" style={{ color: "var(--text-1)", fontSize: 16, lineHeight: 1.65, maxWidth: 620, margin: 0 }}>
          Eight agents that ship deliverables, not chat logs. Pay once for a perpetual license,
          deploy on your VPS, and keep client data off our infrastructure.
        </p>
      </section>

      <section className="container" id="pricing" style={{ paddingBottom: 48 }}>
        <h2 className="serif" style={{ fontSize: 28, margin: "0 0 20px" }}>Pricing</h2>
        <div className="desk-grid">
          <DeskPricingCard
            featured
            title="Lifetime license"
            price="$997"
            suffix="one-time"
            features={[
              "Perpetual commercial license to the Desk distribution",
              "White-glove install on your VPS (remote session)",
              "Atlas + 4 agents pre-configured",
              "2-hour training + 30 days post-launch tuning",
            ]}
          >
            <label className="desk-agent-label" htmlFor="desk-agent-code">
              Sales agent code (optional)
            </label>
            <input
              id="desk-agent-code"
              className="desk-agent-input"
              type="text"
              placeholder="e.g. JANE"
              maxLength={64}
              value={agentCode}
              onChange={(e) => setAgentCode(e.target.value)}
            />
            <button
              type="button"
              className="btn btn-gold"
              style={{ width: "100%", marginTop: 14 }}
              disabled={loading}
              onClick={buyLifetime}
            >
              {loading ? "Opening checkout…" : "Buy lifetime license"} <I name="arrow" size={14} />
            </button>
          </DeskPricingCard>

          <DeskPricingCard
            title="Support Essential"
            price="$99"
            suffix="/ month"
            features={[
              "Email support + security patches",
              "Monthly image upgrades",
              "1 hour per month of agent tuning",
              "Add after purchase via onboarding email",
            ]}
          >
            <a
              className="btn btn-ghost"
              style={{ width: "100%", marginTop: 14, justifyContent: "center" }}
              href="mailto:simeon@elevenviews.io?subject=Desk%20Support%20Essential"
            >
              Ask about support
            </a>
          </DeskPricingCard>

          <DeskPricingCard
            title="Team license"
            price="$4,997"
            suffix="one-time"
            features={[
              "All 8 default agents + 1–2 custom agents",
              "One external integration (CRM, calendar, etc.)",
              "60-day tuning + team training (up to 5 people)",
            ]}
          >
            <a
              className="btn btn-ghost"
              style={{ width: "100%", marginTop: 14, justifyContent: "center" }}
              href="mailto:simeon@elevenviews.io?subject=Desk%20Team%20license"
            >
              Talk to sales
            </a>
          </DeskPricingCard>

          <DeskPricingCard
            title="Enterprise"
            price="Custom"
            features={["SSO, custom MCP, source escrow", "White-label reseller terms available"]}
          >
            <a
              className="btn btn-ghost"
              style={{ width: "100%", marginTop: 14, justifyContent: "center" }}
              href="mailto:simeon@elevenviews.io?subject=Desk%20Enterprise"
            >
              Talk to sales
            </a>
          </DeskPricingCard>
        </div>
      </section>

      <section className="container" style={{ paddingBottom: 48 }}>
        <h2 className="serif" style={{ fontSize: 24, margin: "0 0 16px" }}>Monthly infra (paid to vendors, not us)</h2>
        <div style={{ overflowX: "auto" }}>
          <table className="desk-table">
            <thead>
              <tr>
                <th>Service</th>
                <th>Typical cost</th>
              </tr>
            </thead>
            <tbody>
              {[
                ["VPS (16 GB recommended)", "$14–24"],
                ["Neon Postgres", "$19"],
                ["Wasabi storage", "$7"],
                ["Resend email", "$20"],
                ["Cursor + Anthropic APIs", "$70–310"],
              ].map(([svc, cost]) => (
                <tr key={svc}>
                  <td>{svc}</td>
                  <td className="mono">{cost}</td>
                </tr>
              ))}
              <tr>
                <td><strong>Realistic total</strong></td>
                <td className="mono"><strong>$130–380</strong></td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section className="container" style={{ paddingBottom: 48 }}>
        <h2 className="serif" style={{ fontSize: 24, margin: "0 0 16px" }}>What is in the box</h2>
        <div className="desk-card" style={{ borderColor: "var(--border)" }}>
          <ul className="desk-features" style={{ color: "var(--text-1)" }}>
            {[
              "Multi-agent web UI on your domain",
              "Atlas, Aura, Research, Database, Coder, Briefing, HQ personas",
              "Deliverable tools: ev-pdf, ev-png, ev-pptx, ev-email, ev-pr, ev-img-gen",
              "Telegram bridge, Resend email, S3 brand library",
              "Issue board, projects, leads CRM, pipeline tracker",
            ].map((item) => (
              <li key={item}>{item}</li>
            ))}
          </ul>
        </div>
      </section>

      <section className="container" id="faq" style={{ paddingBottom: 80 }}>
        <h2 className="serif" style={{ fontSize: 24, margin: "0 0 16px" }}>FAQ</h2>
        <dl className="desk-faq">
          <dt>Do I own the software?</dt>
          <dd>
            You receive a perpetual license to run the Desk distribution on infrastructure you control.
            We retain IP in the compiled product, personas, and trademarks. You own your data, brand assets, and configurations.
          </dd>
          <dt>Can I resell Desk to my clients?</dt>
          <dd>Not on the standard license. White-label reseller terms are available on Enterprise.</dd>
          <dt>What happens if I cancel support?</dt>
          <dd>
            Your license stays perpetual. You stop receiving new image pulls until you resubscribe. Installed images keep running.
          </dd>
          <dt>How fast can I go live?</dt>
          <dd>
            Most installs complete in one 30-minute remote session after we issue your deploy token (within 24 business hours of payment).
          </dd>
        </dl>
        <p style={{ marginTop: 32, fontSize: 13, color: "var(--text-3)" }}>
          Product:{" "}
          <a href="https://github.com/Dongetabag/eleven-views-desk" className="lk">
            eleven-views-desk
          </a>
          {" · "}
          <a href="mailto:simeon@elevenviews.io" className="lk">
            simeon@elevenviews.io
          </a>
        </p>
      </section>
    </main>
  );
}

window.Desk = Desk;
