/* @jsx React.createElement */
// Shared Nav + Footer + small atoms for INDIE Labs.

const WA_NUMBER = "628976046500"; // wa.me uses no leading 0 — user: 08976046500
const WA_DISPLAY = "0897 6046 500";
const EMAIL = "info@indielabs.id";
const WA_LINK = (msg = "Halo INDIE Labs, saya tertarik diskusi proyek.") =>
  `https://wa.me/${WA_NUMBER}?text=${encodeURIComponent(msg)}`;

const INDIELABS_SUPABASE_URL = "https://indie.supabase.co";
const INDIELABS_SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Indsc3pqdnZveXltd2dwbXRnd2V4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ1ODg5OTcsImV4cCI6MjA5MDE2NDk5N30.5emUfc2jlLxutLhtGZFD0Rq3MOUl4JAcU3Fd5RydjRU";

// Lightweight, non-blocking auth state hook for navbar.
// Returns: { state: "unknown" | "anon" | "user" }
function useLabsAuth() {
  const [state, setState] = React.useState("unknown");
  React.useEffect(() => {
    let cancelled = false;
    function check() {
      if (cancelled) return;
      if (!window.supabase || !window.supabase.createClient) {
        // Supabase UMD belum siap — coba lagi sebentar, kalau gagal anggap anon.
        setTimeout(check, 400);
        return;
      }
      try {
        const c = window.supabase.createClient(INDIELABS_SUPABASE_URL, INDIELABS_SUPABASE_ANON_KEY);
        c.auth.getSession().then((res) => {
          if (cancelled) return;
          setState(res && res.data && res.data.session ? "user" : "anon");
        }).catch(() => { if (!cancelled) setState("anon"); });
      } catch (_) { if (!cancelled) setState("anon"); }
    }
    check();
    return () => { cancelled = true; };
  }, []);
  return state;
}

function NavAuthLink() {
  const state = useLabsAuth();
  if (state === "unknown") {
    // Reserve space tanpa flicker
    return <span style={{ width: 70, display: "inline-block" }} />;
  }
  if (state === "user") {
    return (
      <a href="/dashboard.html" className="navlink"
         style={{ color: "var(--labs-accent)", fontSize: 14, fontWeight: 600, textDecoration: "none" }}>
        Dashboard →
      </a>
    );
  }
  return (
    <a href="/auth/login-redirect.html" className="navlink"
       style={{ color: "var(--labs-fg-2)", fontSize: 14, fontWeight: 500, textDecoration: "none" }}>
      Login
    </a>
  );
}

function LabsMark({ size = 32 }) {
  return (
    <img
      src="assets/logos/indielabs.png"
      alt="INDIE Labs."
      style={{ width: size, height: size, borderRadius: "50%", display: "block" }}
    />
  );
}

function Nav({ current = "home" }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [
    { id: "home",      label: "Home",      href: "index.html" },
    { id: "services",  label: "Services",  href: "services.html" },
    { id: "portfolio", label: "Portfolio", href: "portfolio.html" },
    { id: "contact",   label: "Contact",   href: "contact.html" },
  ];
  return (
    <header className={`nav ${scrolled ? "scrolled" : ""}`}>
      <a href="index.html" style={{ display: "flex", alignItems: "center", gap: 10, textDecoration: "none", color: "var(--labs-fg)" }}>
        <LabsMark size={34} />
        <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 20, letterSpacing: ".01em", textTransform: "uppercase" }}>
            INDIE Labs.
          </span>
          <span className="nav-subtitle" style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: ".18em", color: "var(--labs-fg-3)", marginTop: 3, textTransform: "uppercase" }}>
            R&D · Software
          </span>
        </div>
      </a>
      <nav className="nav-links" style={{ display: "flex", gap: 28, marginLeft: 32 }}>
        {links.map((l) => (
          <a key={l.id} href={l.href} className={`navlink ${current === l.id ? "active" : ""}`}>{l.label}</a>
        ))}
      </nav>
      <div style={{ flex: 1 }} />
      <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
        <NavAuthLink />
        <a href={WA_LINK()} target="_blank" rel="noopener" className="btn btn-primary btn-sm" style={{ boxShadow: "3px 3px 0 #000" }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: "block" }}>
            <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
          </svg>
          Diskusi proyek
        </a>
      </div>
    </header>
  );
}

function Footer() {
  const SUBS = [
    "indiebrand","indiepreneur","indiespace","ims",
    "indieruma","indiekost","indiecafe","indielabs",
    "indiepack","indiepaper","pixelindie","yappari",
  ];
  return (
    <footer className="footer">
      <div className="container">
        <div className="grid-footer">
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
              <LabsMark size={48} />
              <div style={{ fontFamily: "var(--font-display)", fontSize: 28, letterSpacing: ".01em", textTransform: "uppercase", color: "var(--labs-fg)" }}>
                INDIE Labs.
              </div>
            </div>
            <p style={{ color: "var(--labs-fg-2)", fontSize: 14, lineHeight: 1.7, maxWidth: 320, margin: 0 }}>
              We build software for Indonesian businesses — websites, web-apps,
              AI integration. Quiet on the surface. Careful underneath.
            </p>
            <div style={{ marginTop: 18, display: "flex", gap: 10 }}>
              <a href={WA_LINK()} target="_blank" rel="noopener" className="btn btn-ghost btn-sm">WhatsApp</a>
              <a href={`mailto:${EMAIL}`} className="btn btn-ghost btn-sm">Email</a>
            </div>
          </div>

          <FooterCol title="Services" items={[
            ["Web Development", "services.html#web"],
            ["Web App", "services.html#webapp"],
            ["AI Integration", "services.html#ai"],
            ["IT Consultant", "services.html#consult"],
          ]} />
          <FooterCol title="Studio" items={[
            ["Portfolio", "portfolio.html"],
            ["Process", "services.html#process"],
            ["Pricing", "services.html#pricing"],
            ["Contact", "contact.html"],
          ]} />
          <FooterCol title="Reach" items={[
            [WA_DISPLAY, WA_LINK()],
            [EMAIL, `mailto:${EMAIL}`],
            ["Jakarta · Bandung", "#"],
          ]} />
        </div>

        <div className="rule" style={{ margin: "40px 0 24px" }} />

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--labs-fg-3)" }}>
            Part of <span style={{ color: "var(--labs-accent)" }}>INDIE Group</span> · Est. 2026
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            {SUBS.map((id) => (
              <img
                key={id}
                src={`assets/logos/${id}.png`}
                alt={id}
                title={id}
                style={{
                  width: 26, height: 26, borderRadius: "50%",
                  opacity: id === "indielabs" ? 1 : 0.6,
                  outline: id === "indielabs" ? "1.5px solid var(--labs-accent)" : "none",
                  outlineOffset: 2,
                  transition: "opacity 200ms var(--ease-out)",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.opacity = 1)}
                onMouseLeave={(e) => (e.currentTarget.style.opacity = id === "indielabs" ? 1 : 0.6)}
              />
            ))}
          </div>
        </div>
        <div style={{ marginTop: 18, fontSize: 12, color: "var(--labs-fg-4)", display: "flex", gap: 16 }}>
          <span>© 2026 INDIE Labs.</span>
          <span>·</span>
          <span>A small studio doing careful work.</span>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, items }) {
  return (
    <div>
      <div className="eyebrow-dim" style={{ marginBottom: 14 }}>{title}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map(([label, href]) => (
          <li key={label}>
            <a href={href} style={{ color: "var(--labs-fg-2)", textDecoration: "none", fontSize: 14, transition: "color 200ms" }}
               onMouseEnter={(e) => (e.currentTarget.style.color = "var(--labs-accent)")}
               onMouseLeave={(e) => (e.currentTarget.style.color = "var(--labs-fg-2)")}>
              {label}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

Object.assign(window, { Nav, Footer, LabsMark, WA_NUMBER, WA_DISPLAY, EMAIL, WA_LINK });
