
// ========== TAMASHI LANE 1: THE SENSEI'S SCROLLS ==========
// Instant download storefront — /scrolls route
// V2 only: displayed when data-brand-variant='sensei'

function SciScrollCard({ product, onBuy }) {
  const isHighlighted = product.highlighted;
  return (
    React.createElement("div", {
      className: "sci-card-hover",
      style: {
        display: "flex",
        flexDirection: "column",
        padding: "28px 32px",
        background: isHighlighted ? "#0a0a0a" : "transparent",
        color: isHighlighted ? "#f5f1ea" : SCI.ink,
        border: `1px solid ${SCI.border}`,
        position: "relative",
      },
    },
      isHighlighted && React.createElement("div", {
        style: {
          position: "absolute",
          top: -1,
          right: -1,
          background: SCI.orange,
          color: SCI.paper,
          fontFamily: SCI.mono,
          fontSize: 9,
          letterSpacing: 0.8,
          textTransform: "uppercase",
          padding: "5px 12px",
          border: `1px solid ${SCI.border}`,
        },
      }, "Most chosen"),
      React.createElement("div", {
        style: {
          fontFamily: SCI.mono,
          fontSize: 10,
          letterSpacing: 0.8,
          textTransform: "uppercase",
          opacity: 0.6,
          marginBottom: 8,
        },
      }, product.type),
      React.createElement("div", {
        style: {
          fontFamily: SCI.display,
          fontSize: 28,
          lineHeight: 1.1,
          letterSpacing: -0.4,
          marginBottom: 12,
        },
      }, product.name),
      React.createElement("div", {
        style: { fontSize: 14, lineHeight: 1.6, opacity: 0.85, marginBottom: 20, flex: 1 },
      }, product.description),
      React.createElement("div", {
        style: { display: "flex", alignItems: "baseline", gap: 6, marginBottom: 20 },
      },
        React.createElement("span", {
          style: {
            fontFamily: SCI.display,
            fontSize: 48,
            lineHeight: 0.9,
            letterSpacing: -1.2,
          },
        }, `$${Math.round(product.price / 100)}`),
        React.createElement("span", { style: { fontFamily: SCI.mono, fontSize: 11, opacity: 0.6 } }, "/one time"),
      ),
      React.createElement("button", {
        className: "sci-btn",
        onClick: onBuy,
        style: {
          width: "100%",
          padding: "14px 0",
          background: isHighlighted ? SCI.orange : SCI.ink,
          color: isHighlighted ? SCI.paper : SCI.paper,
          fontFamily: SCI.mono,
          fontSize: 12,
          letterSpacing: 0.8,
          textTransform: "uppercase",
          border: "none",
          cursor: "pointer",
        },
      }, isHighlighted ? "Download" : "Add to Scrolls"),
    )
  );
}

function ScrollsGrid({ products, onBuy }) {
  return (
    React.createElement("div", {
      style: {
        maxWidth: 1200,
        margin: "0 auto",
        padding: "0 32px",
      },
    },
      React.createElement("div", {
        style: {
          padding: "64px 0 24px",
          textAlign: "center",
        },
      },
        React.createElement("div", {
          style: { fontFamily: SCI.mono, fontSize: 10, letterSpacing: 1, textTransform: "uppercase", opacity: 0.5, marginBottom: 12 },
        }, "§ 01 · Lane 1"),
        React.createElement("h1", {
          style: {
            fontFamily: SCI.display,
            fontSize: "clamp(36px, 5vw, 64px)",
            lineHeight: 1.05,
            letterSpacing: -1.2,
            margin: "0 0 16px",
            fontWeight: 500,
          },
        }, "The Sensei's ", React.createElement("span", { style: { fontStyle: "italic" } }, "Scrolls")),
        React.createElement("p", {
          style: { fontSize: 16, lineHeight: 1.6, opacity: 0.7, maxWidth: 520, margin: "0 auto", color: SCI.ink2 },
        }, "Zero friction. Instant clarity. Premium PDFs and audio scrolls you can read right now — no birth chart required."),
      ),
      React.createElement("div", {
        style: {
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
          gap: 0,
          borderTop: `1px solid ${SCI.border}`,
          borderLeft: `1px solid ${SCI.border}`,
          marginBottom: 80,
        },
      }, products.map((p, i) =>
        React.createElement("div", {
          key: p.slug,
          style: { borderRight: `1px solid ${SCI.border}`, borderBottom: `1px solid ${SCI.border}` },
        },
          React.createElement(SciScrollCard, {
            product: p,
            onBuy: () => onBuy(p),
          }),
        )
      )),
    )
  );
}

function ScrollsPage({ onNavigate, user, onSignIn }) {
  // Products: seeded from Supabase digital_products table
  // Requires authentication to access
  const [products, setProducts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  // Check authentication
  if (!user) {
    return React.createElement("div", {
      style: { minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: SCI.mono, fontSize: 12, textAlign: "center", padding: "40px" },
    },
      React.createElement("div", {},
        React.createElement("div", { style: { opacity: 0.6, marginBottom: 20 } }, "Sign in to access your scrolls."),
        React.createElement("button", {
          onClick: onSignIn,
          style: {
            padding: "10px 24px",
            background: SCI.ink,
            color: SCI.paper,
            border: "none",
            fontFamily: SCI.mono,
            fontSize: 11,
            letterSpacing: 0.8,
            cursor: "pointer",
          },
        }, "SIGN IN"),
      ),
    );
  }

  React.useEffect(() => {
    const config = window.TAMASHI_CONFIG || {};
    let cancelled = false;
    async function load() {
      try {
        const { createClient } = window.supabase ?? await import("https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/+esm");
        const client = createClient(config.supabaseUrl, config.supabaseAnonKey);
        const { data, error } = await client
          .from("digital_products")
          .select("id, name, slug, description, price, file_type, type, category")
          .eq("is_active", true)
          .order("price", { ascending: true });
        if (cancelled) return;
        if (error) throw error;
        setProducts(data || []);
      } catch (e) {
        if (!cancelled) setError(e.message);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => { cancelled = true; };
  }, []);

  const handleBuy = async (product) => {
    try {
      const config = window.TAMASHI_CONFIG || {};
      const res = await fetch(`${config.supabaseUrl}/functions/v1/create-checkout-session`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${config.supabaseAnonKey}`,
        },
        body: JSON.stringify({
          stripe_price_id: product.stripe_price_id || "instant_downloads_starter_pack",
          product_slug: product.slug,
          email: null, // let Stripe collect
        }),
      });
      const json = await res.json();
      if (json.url) window.location.href = json.url;
      else throw new Error(json.error || "No checkout URL");
    } catch (e) {
      alert("Checkout error: " + e.message);
    }
  };

  if (loading) {
    return React.createElement("div", {
      style: { minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: SCI.mono, fontSize: 12, opacity: 0.5 },
    }, "Loading scrolls...");
  }
  if (error) {
    return React.createElement("div", {
      style: { minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: SCI.mono, fontSize: 12, color: SCI.orange },
    }, "Error loading scrolls — ", error);
  }
  if (!products || products.length === 0) {
    return React.createElement("div", {
      style: { minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: SCI.mono, fontSize: 12, opacity: 0.5 },
    }, "No scrolls available yet. Coming soon.");
  }

  return React.createElement("div", { style: { paddingTop: 0, background: SCI.paper, minHeight: "100vh" } },
    React.createElement(ScrollsGrid, { products, onBuy: handleBuy }),
    React.createElement("div", {
      style: {
        maxWidth: 1200,
        margin: "0 auto",
        padding: "0 32px 80px",
        display: "flex",
        gap: 20,
        justifyContent: "center",
      },
    },
      React.createElement("button", {
        className: "sci-link-btn",
        onClick: () => onNavigate && onNavigate("/"),
        style: {
          fontFamily: SCI.mono,
          fontSize: 12,
          letterSpacing: 0.5,
          color: SCI.ink2,
          padding: "8px 0",
        },
      }, "← Return to Home"),
    ),
    React.createElement("div", {
      style: { textAlign: "center", padding: "24px 0 48px", borderTop: `1px solid ${SCI.border}` },
    },
      React.createElement("div", { style: { fontFamily: SCI.mono, fontSize: 10, letterSpacing: 0.5, opacity: 0.5, textTransform: "uppercase" } }, 
        "Tamashi (魂) · Read the signs. Protect your peace."
      ),
    ),
  );
}

// Expose for runtime access
window.SciScrollCard = SciScrollCard;
window.ScrollsGrid = ScrollsGrid;
window.ScrollsPage = ScrollsPage;
