// sculptor.jsx — Creator / "about the maker" page.
// Data sources: diaval_creator (config), diaval_creator_paragraphs (narrative),
// diaval_creator_facts (fact rows), diaval_creator_psalms, diaval_creator_offerings.
// Sections toggle via show_shrine / show_psalms / show_offerings / show_benediction in diaval_creator.

function SculptorPage({ tab, onTabChange }) {
  const S = window.shellStyles;
  const { isMobile } = (window.useViewport ? window.useViewport() : { isMobile: false });
  const renderInline = window.renderAboutInline; // reuse the inline-html renderer from about.jsx
  const [activePsalm, setActivePsalm] = React.useState(0);

  const [config, setConfig] = React.useState(null);
  const [paragraphs, setParagraphs] = React.useState([]);
  const [facts, setFacts] = React.useState([]);
  const [psalms, setPsalms] = React.useState([]);
  const [offerings, setOfferings] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [loadError, setLoadError] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const sb = window.diavalSupabase;
        const [cfg, paras, fctRows, psm, off] = await Promise.all([
          sb.from("diaval_creator").select("*").eq("id", 1).maybeSingle(),
          sb.from("diaval_creator_paragraphs").select("id, body, position").eq("is_visible", true).order("position", { ascending: true }),
          sb.from("diaval_creator_facts").select("id, label, value, accent, position").eq("is_visible", true).order("position", { ascending: true }),
          sb.from("diaval_creator_psalms").select("id, numeral, title, body, position").eq("is_visible", true).order("position", { ascending: true }),
          sb.from("diaval_creator_offerings").select("id, time, date, item, ritual, position").eq("is_visible", true).order("position", { ascending: true }),
        ]);
        if (cancelled) return;
        if (cfg.error) throw cfg.error;
        if (paras.error) throw paras.error;
        if (fctRows.error) throw fctRows.error;
        if (psm.error) throw psm.error;
        if (off.error) throw off.error;
        setConfig(cfg.data || null);
        setParagraphs(paras.data || []);
        setFacts(fctRows.data || []);
        setPsalms(psm.data || []);
        setOfferings(off.data || []);
      } catch (err) {
        if (!cancelled) setLoadError(err.message);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  if (loading) {
    return (
      <Shell tab={tab} onTabChange={onTabChange} page="007" broadcast="ABOUT THE CREATOR">
        <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, color: S.ashDim, letterSpacing: "0.3em" }}>
          ⸺ TUNING SIGNAL ⸺
        </div>
      </Shell>
    );
  }
  if (loadError || !config) {
    return (
      <Shell tab={tab} onTabChange={onTabChange} page="007" broadcast="ABOUT THE CREATOR">
        <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 12, padding: 40 }}>
          <div style={{ fontSize: 13, color: S.bloodHot, letterSpacing: "0.3em" }}>◢ FEED CORRUPTED</div>
          <div style={{ fontSize: 13, color: S.ash, fontStyle: "italic", maxWidth: 600, textAlign: "center" }}>{loadError || "no config"}</div>
        </div>
      </Shell>
    );
  }

  const psalm = psalms[activePsalm] || psalms[0];

  return (
    <Shell tab={tab} onTabChange={onTabChange} page="007" broadcast="ABOUT THE CREATOR">
      <div style={{
        position: isMobile ? "relative" : "absolute",
        inset: isMobile ? "auto" : 0,
        overflow: isMobile ? "visible" : "auto",
      }}>
        {/* page header */}
        <div style={{ padding: isMobile ? "20px 16px 16px" : "32px 56px 20px", borderBottom: `1px solid ${S.concreteHi}` }}>
          <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.3em", marginBottom: 8 }}>
            {config.hero_eyebrow}
          </div>
          <div style={{ display: "flex", flexDirection: isMobile ? "column" : "row", justifyContent: "space-between", alignItems: isMobile ? "flex-start" : "flex-end", gap: isMobile ? 12 : 32 }}>
            <h2 style={{
              margin: 0, fontFamily: S.display, fontSize: isMobile ? 28 : 56, lineHeight: 0.92,
              letterSpacing: "-0.02em", color: S.bone,
            }}>
              {config.hero_title_main}<span style={{ color: S.bloodHot }}>{config.hero_title_accent}</span>
            </h2>
            {config.hero_sidebar && (
              <div style={{ fontSize: 13, color: S.ash, letterSpacing: "0.04em", maxWidth: 380, lineHeight: 1.5 }}>
                {renderInline ? renderInline(config.hero_sidebar, S) : config.hero_sidebar}
              </div>
            )}
          </div>
        </div>

        {/* PART ONE — portrait + narrative (mirrors About) */}
        {config.show_shrine && (
        <section style={{
          padding: isMobile ? "32px 16px 28px" : "48px 56px 40px",
          display: "grid",
          // Stack on mobile (portrait above narrative) — same template as About.
          gridTemplateColumns: isMobile ? "1fr" : "300px 1fr",
          gap: isMobile ? 24 : 56,
        }}>
          {/* portrait column */}
          <div style={{ width: "100%", maxWidth: isMobile ? 240 : "100%", margin: isMobile ? "0 auto" : 0 }}>
            <div style={{
              position: "relative", width: "100%", aspectRatio: "3 / 4",
              border: `1px solid ${S.concreteHi}`, overflow: "hidden",
              background: "linear-gradient(180deg, #1a1014 0%, #050505 100%)",
            }}>
              {config.portrait_url ? (
                <img
                  src={config.portrait_url}
                  alt={config.portrait_top_label || "portrait"}
                  style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.7 }}
                />
              ) : (
                <svg viewBox="0 0 280 376" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
                  <defs>
                    <radialGradient id="sculptor-halo-v2" cx="50%" cy="32%" r="55%">
                      <stop offset="0%" stopColor="#e8e2d0" stopOpacity="0.25" />
                      <stop offset="100%" stopColor="#e8e2d0" stopOpacity="0" />
                    </radialGradient>
                  </defs>
                  <rect width="280" height="376" fill="url(#sculptor-halo-v2)" />
                  <path d="M40 376 L40 300 Q70 270 110 260 L110 240 Q90 230 90 198 Q90 150 140 145 Q190 150 190 198 Q190 230 170 240 L170 260 Q210 270 240 300 L240 376 Z"
                    fill="#0a0a0a" stroke="#e8e2d0" strokeWidth="0.4" strokeOpacity="0.5" />
                  <ellipse cx="140" cy="180" rx="48" ry="55" fill="#1f1418" stroke="#e8e2d0" strokeWidth="0.3" strokeOpacity="0.4" />
                  {Array.from({ length: 14 }).map((_, i) => (
                    <path key={i} d={`M${100 + i * 5} 130 Q${108 + i * 5} ${148 - (i % 4) * 5} ${112 + i * 5} 188`}
                      stroke="#0a0a0a" strokeWidth="2.2" fill="none" strokeLinecap="round" />
                  ))}
                  <path d="M120 178 Q124 174 130 178" stroke="#e8e2d0" strokeWidth="0.8" fill="none" />
                  <path d="M150 178 Q154 174 160 178" stroke="#e8e2d0" strokeWidth="0.8" fill="none" />
                  <g stroke="#be211e" strokeWidth="0.5" fill="none">
                    <line x1="20" y1="20" x2="36" y2="20" />
                    <line x1="28" y1="12" x2="28" y2="28" />
                  </g>
                </svg>
              )}
              <div style={{ position: "absolute", inset: 0, filter: "url(#ind-noise)", opacity: 0.4, mixBlendMode: "overlay", pointerEvents: "none" }} />
              <div style={{ position: "absolute", bottom: 14, left: 14, fontSize: 12, color: S.bone, letterSpacing: "0.25em", lineHeight: 1.7, textShadow: "0 1px 4px rgba(0,0,0,0.7)" }}>
                {config.portrait_bottom_label}
              </div>
            </div>
          </div>

          {/* narrative column */}
          <div>
            <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.4em", marginBottom: 8 }}>
              {config.narrative_eyebrow}
            </div>
            <h3 style={{
              margin: 0, fontFamily: S.display, fontSize: isMobile ? 22 : 36, color: S.bone,
              letterSpacing: "-0.01em", lineHeight: 1, marginBottom: isMobile ? 16 : 24,
            }}>
              {config.narrative_title_main}<span style={{ color: S.bloodHot }}>{config.narrative_title_accent}</span>
            </h3>

            <div style={{ fontFamily: S.meta, fontSize: 14, lineHeight: 1.85, color: S.bone, letterSpacing: "0.005em" }}>
              {paragraphs.map((p, i) => (
                <p key={p.id} style={{ margin: 0, marginBottom: 18 }}>
                  {renderInline ? renderInline(p.body, S) : p.body}
                </p>
              ))}
            </div>

            {/* Facts inline at the bottom of the narrative */}
            {facts.length > 0 && (
              <div style={{ marginTop: 32, border: `1px solid ${S.concreteHi}`, background: S.raven }}>
                <div style={{
                  padding: "10px 16px", borderBottom: `1px solid ${S.concreteHi}`,
                  background: S.concrete, fontSize: 12, letterSpacing: "0.3em", color: S.bloodHot,
                }}>
                  ◢ {config.facts_eyebrow ? config.facts_eyebrow.replace(/^◢\s*/, "") : "FACTS"}
                </div>
                <div>
                  {facts.map((f, i) => (
                    <div key={f.id} style={{
                      display: "grid", gridTemplateColumns: isMobile ? "1fr" : "200px 1fr",
                      padding: "10px 16px",
                      borderBottom: i === facts.length - 1 ? "none" : `1px dashed ${S.concreteHi}`,
                      gap: 18, alignItems: "baseline",
                    }}>
                      <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.3em", fontFamily: S.meta }}>
                        {f.label}
                      </div>
                      <div style={{
                        fontSize: 13, color: f.accent ? S.bloodHot : S.bone,
                        fontFamily: S.meta, letterSpacing: "0.02em", lineHeight: 1.4,
                      }}>
                        {f.value}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </section>
        )}

        {/* PSALMS — kept toggleable, hidden by default after the rewrite */}
        {config.show_psalms && psalms.length > 0 && (
        <section style={{ padding: isMobile ? "28px 16px" : "48px 56px", borderTop: `1px solid ${S.concreteHi}`, background: `linear-gradient(180deg, ${S.raven} 0%, #050505 100%)` }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 32, gap: 24 }}>
            <div>
              <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.4em", marginBottom: 8 }}>
                {config.psalms_eyebrow}
              </div>
              <h3 style={{ margin: 0, fontFamily: S.display, fontSize: 32, color: S.bone, letterSpacing: "-0.01em" }}>
                {config.psalms_title_main}<span style={{ color: S.bloodHot }}>{config.psalms_title_accent}</span>
              </h3>
            </div>
            <div style={{ display: "flex", gap: 8 }}>
              {psalms.map((p, i) => (
                <button key={p.id} onClick={() => setActivePsalm(i)} style={{
                  width: 44, height: 44, fontFamily: S.display, fontSize: 16,
                  background: activePsalm === i ? S.bloodHot : "transparent",
                  border: `1px solid ${activePsalm === i ? S.bloodHot : S.concreteHi}`,
                  color: activePsalm === i ? S.bone : S.ash, cursor: "pointer",
                  letterSpacing: "0.02em",
                }}>
                  {p.numeral}
                </button>
              ))}
            </div>
          </div>

          <div style={{
            border: `1px solid ${S.concreteHi}`, borderLeft: `3px solid ${S.bloodHot}`,
            background: S.raven, padding: "44px 56px",
            display: "grid",
            gridTemplateColumns: isMobile ? "1fr" : "120px 1fr",
            gap: isMobile ? 16 : 40,
          }}>
            <div>
              <div style={{ fontFamily: S.display, fontSize: 96, color: S.bloodHot, letterSpacing: "-0.02em", lineHeight: 0.85 }}>
                {psalm.numeral}
              </div>
            </div>
            <div>
              <h4 style={{ margin: 0, fontFamily: S.display, fontSize: 28, color: S.bone, letterSpacing: "-0.01em", marginBottom: 20 }}>
                {psalm.title}
              </h4>
              <pre style={{
                margin: 0, fontFamily: S.meta, fontSize: 15, color: S.bone,
                lineHeight: 1.85, letterSpacing: "0.005em", whiteSpace: "pre-wrap",
              }}>
                {psalm.body}
              </pre>
            </div>
          </div>
        </section>
        )}

        {/* OFFERINGS LOG — toggleable */}
        {config.show_offerings && offerings.length > 0 && (
        <section style={{ padding: isMobile ? "28px 16px" : "48px 56px", borderTop: `1px solid ${S.concreteHi}`, background: `linear-gradient(180deg, ${S.raven}, #050505)` }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24, gap: 24 }}>
            <div>
              {config.offerings_eyebrow && (
                <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.4em", marginBottom: 8 }}>
                  {config.offerings_eyebrow}
                </div>
              )}
              {(config.offerings_title_main || config.offerings_title_accent) && (
                <h3 style={{ margin: 0, fontFamily: S.display, fontSize: 32, color: S.bone, letterSpacing: "-0.01em" }}>
                  {config.offerings_title_main}<span style={{ color: S.bloodHot }}>{config.offerings_title_accent}</span>
                </h3>
              )}
              {config.offerings_subtitle && (
                <div style={{ marginTop: 8, fontSize: 13, color: S.ash, fontStyle: "italic" }}>
                  {config.offerings_subtitle}
                </div>
              )}
            </div>
          </div>

          <div style={{ border: `1px solid ${S.concreteHi}` }}>
            <div style={{
              display: "grid", gridTemplateColumns: "100px 110px 1fr 1.4fr",
              padding: "10px 18px", borderBottom: `1px solid ${S.concreteHi}`,
              background: S.concrete, fontSize: 12, color: S.ashDim, letterSpacing: "0.3em",
            }}>
              <div>TIME</div><div>DATE</div><div>OFFERING</div><div>RITUAL</div>
            </div>
            {offerings.map((o, i) => (
              <div key={o.id} style={{
                display: "grid", gridTemplateColumns: "100px 110px 1fr 1.4fr",
                padding: "16px 18px",
                borderBottom: i < offerings.length - 1 ? `1px solid ${S.concreteHi}` : "none",
                fontSize: 13, color: S.bone, fontFamily: S.meta, letterSpacing: "0.02em", lineHeight: 1.5,
              }}>
                <div style={{ color: S.bloodHot, fontFamily: S.display }}>{o.time}</div>
                <div style={{ color: S.ash, fontSize: 13 }}>{o.date}</div>
                <div style={{ color: S.bone }}>{o.item}</div>
                <div style={{ color: S.ash, fontStyle: "italic" }}>{o.ritual}</div>
              </div>
            ))}
          </div>
        </section>
        )}

        {/* BENEDICTION — toggleable */}
        {config.show_benediction && (
        <section style={{ padding: "56px 56px 72px", borderTop: `1px solid ${S.concreteHi}`, textAlign: "center" }}>
          {config.benediction_eyebrow && (
            <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.5em", marginBottom: 20 }}>
              {config.benediction_eyebrow}
            </div>
          )}
          <div style={{
            fontFamily: S.display, fontSize: 44, color: S.bone, letterSpacing: "-0.015em",
            lineHeight: 1.05, maxWidth: 920, margin: "0 auto",
          }}>
            {renderInline ? renderInline(config.benediction_html, S) : config.benediction_html}
          </div>
          {config.benediction_signoff && (
            <div style={{ marginTop: 32, fontSize: 13, color: S.ash, letterSpacing: "0.3em", fontFamily: S.meta }}>
              {config.benediction_signoff}
            </div>
          )}
          {config.benediction_links && (
            <div style={{ marginTop: 14, fontSize: 12, color: S.ashDim, letterSpacing: "0.3em" }}>
              {config.benediction_links}
            </div>
          )}
        </section>
        )}
      </div>
    </Shell>
  );
}

window.SculptorPage = SculptorPage;
