/* janoberg.art — shared bundle. Defines all components and mountPage().
   Each page HTML calls window.mountPage('home', { base: './' }) etc. */
/* global React, ReactDOM, WORKS, SERIES */
const { useState } = React;

// ───── url helpers ─────
function url(base, path) {
  // path like "verk/bohuslan/" or "om.html" — base already trailing-slash
  if (path === "") return base + "index.html";
  return base + path;
}
const seriesUrl = (b, sid) => url(b, `verk/${sid}/`);
const workUrl = (b, w) => url(b, `verk/${w.series}/${w.slug}.html`);

// ───── shared chrome ─────
function Nav({ active, lang = "SE", scope = "desktop", base }) {
  const items = [
    { id: "verk", se: "Verk", en: "Work", href: url(base, "verk/") },
    { id: "om", se: "Om", en: "About", href: url(base, "om.html") },
    { id: "boken", se: "Boken", en: "The Book", href: url(base, "boken.html") },
    { id: "kop", se: "Köp", en: "Shop", href: url(base, "kop.html") },
    { id: "kontakt", se: "Kontakt", en: "Contact", href: url(base, "kontakt.html") }
  ];
  if (scope === "mobile") {
    return (
      <div className="nav" style={{ padding: "18px 20px" }}>
        <a href={url(base, "")} className="nav-brand" style={{ fontSize: 16 }}>
          Jan Öberg
          <span className="small" style={{ fontSize: 9, marginTop: 1 }}>akvarell</span>
        </a>
        <button id="nav-toggle" aria-label="Meny" style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          <span style={{ width: 20, height: 1, background: "var(--ink)" }} />
          <span style={{ width: 20, height: 1, background: "var(--ink)" }} />
        </button>
        <MobileMenuPanel items={items} base={base} lang={lang} />
      </div>
    );
  }
  return (
    <div className="nav">
      <a href={url(base, "")} className="nav-brand">
        Jan Öberg
        <span className="small">Akvarell · Watercolour</span>
      </a>
      <div className="nav-links">
        {items.map(i => (
          <a key={i.id} href={i.href} className={active === i.id ? "active" : ""}>{lang === "SE" ? i.se : i.en}</a>
        ))}
      </div>
      <div className="nav-meta">
        <a href="https://instagram.com/janoberg1" target="_blank" rel="noopener" className="lang">Instagram</a>
      </div>
    </div>
  );
}

function MobileMenuPanel({ items, base, lang }) {
  const [open, setOpen] = useState(false);
  React.useEffect(() => {
    const t = document.getElementById("nav-toggle");
    if (!t) return;
    const h = (e) => { e.preventDefault(); setOpen(o => !o); };
    t.addEventListener("click", h);
    return () => t.removeEventListener("click", h);
  }, []);
  if (!open) return null;
  return (
    <div style={{ position: "fixed", inset: 0, background: "var(--paper)", zIndex: 100, padding: "60px 24px", display: "flex", flexDirection: "column", gap: 8 }}>
      <button onClick={() => setOpen(false)} style={{ position: "absolute", top: 18, right: 20, fontSize: 22 }}>×</button>
      {items.map(i => (
        <a key={i.id} href={i.href} className="serif" style={{ fontSize: 28, padding: "10px 0", borderBottom: "1px solid var(--rule)" }}>
          {lang === "SE" ? i.se : i.en}
        </a>
      ))}
      <div style={{ marginTop: 24, fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-soft)" }}>
        <a href="https://instagram.com/janoberg1" target="_blank" rel="noopener">Instagram · @janoberg1</a>
      </div>
    </div>
  );
}

function Footer({ scope = "desktop", base }) {
  if (scope === "mobile") {
    return (
      <div style={{ borderTop: "1px solid var(--rule)", padding: "32px 20px", fontSize: 12, color: "var(--ink-soft)" }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 18, color: "var(--ink)", marginBottom: 16 }}>Nya verk i inkorgen</div>
        <form className="signup" style={{ display: "flex", borderBottom: "1px solid var(--ink)", marginBottom: 24 }} onSubmit={e=>{e.preventDefault();alert('Tack! Bekräftelse skickad.');}}>
          <input style={{ flex: 1, background: "none", border: "none", outline: "none", fontSize: 13 }} placeholder="din@epost.se" required type="email" />
          <button style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase" }}>Anmäl →</button>
        </form>
        <p style={{ marginBottom: 4 }}>Stenungsund, Sverige</p>
        <p style={{ marginBottom: 4 }}>Member · Svenska Konstnärsförbundet</p>
        <p style={{ marginBottom: 16 }}><a href="https://instagram.com/janoberg1" target="_blank" rel="noopener">Instagram · @janoberg1</a></p>
        <p style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-soft)" }}>© 2026 Jan Öberg · janoberg.art</p>
      </div>
    );
  }
  return (
    <div className="footer">
      <div>
        <h5>Ateljé</h5>
        <p>Jan Öberg</p>
        <p>Stenungsund, Sverige</p>
        <p><a href="mailto:jan@janoberg.art">jan@janoberg.art</a></p>
      </div>
      <div>
        <h5>Verk</h5>
        {SERIES.filter(s => s.id !== "arkiv").map(s => (
          <p key={s.id}><a href={seriesUrl(base, s.id)}>{s.name_se}</a></p>
        ))}
      </div>
      <div>
        <h5>Förbund</h5>
        <p>Member, Svenska<br/>Konstnärsförbundet</p>
        <p style={{ marginTop: 12 }}>Instagram</p>
        <p><a href="https://instagram.com/janoberg1" target="_blank" rel="noopener">@janoberg1</a></p>
      </div>
      <div>
        <h5>Nya verk</h5>
        <p style={{ marginBottom: 14 }}>Brev fyra gånger om året när nya verk publiceras. Inget annat.</p>
        <form className="signup" onSubmit={e=>{e.preventDefault();alert('Tack! Bekräftelse skickad.');}}>
          <input placeholder="din@epost.se" required type="email" />
          <button>Anmäl →</button>
        </form>
        <p style={{ fontSize: 11, marginTop: 28, color: "var(--ink-soft)" }}>© 2026 Jan Öberg · janoberg.art</p>
      </div>
    </div>
  );
}

// ───── primitives ─────
function Paper({ src, ratio, padding = 28 }) {
  return (
    <div className="paper-frame" style={{ padding, background: "#fff" }}>
      <img src={src} style={{ aspectRatio: String(ratio) }} alt="" loading="lazy" />
    </div>
  );
}

function PriceLine({ work }) {
  if (work.status === "sold") {
    return <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}><span className="tag sold">SÅLD</span><span style={{ fontSize: 12, color: "var(--ink-soft)" }}>{work.sold_year}</span></div>;
  }
  if (work.status === "private") return <span className="tag">PRIVAT SAMLING</span>;
  return <div className="serif" style={{ fontSize: 22 }}>{work.price_sek?.toLocaleString("sv-SE")} <span style={{ fontSize: 12, fontFamily: "var(--sans)", letterSpacing: "0.12em", color: "var(--ink-soft)" }}>SEK</span></div>;
}

function CommerceBlock({ work, base }) {
  const [tab, setTab] = useState("original");
  const [size, setSize] = useState("A3");
  const printPrices = { A4: 1200, A3: 1800, A2: 2600 };
  const sold = work.status === "sold" || work.status === "private";
  const inquireHref = `mailto:jan@janoberg.art?subject=${encodeURIComponent(`Förfrågan: ${work.title_se}${work.title_en ? ' / '+work.title_en : ''}, ${work.year}`)}&body=${encodeURIComponent(`Hej Jan,\n\nJag är intresserad av originalverket "${work.title_se}"${work.title_en ? ' ('+work.title_en+')' : ''}, ${work.year}, ${work.dim || ''}.\n\nLänk: https://janoberg.art${workUrl(base, work).replace(/^\.\//,'/')}\n\nHälsningar,\n`)}`;
  return (
    <div style={{ borderTop: "1px solid var(--rule)", borderBottom: "1px solid var(--rule)", padding: "32px 0" }}>
      <div style={{ display: "flex", gap: 28, marginBottom: 24, fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-soft)" }}>
        <button onClick={() => setTab("original")} style={{ paddingBottom: 6, borderBottom: tab === "original" ? "1px solid var(--ink)" : "1px solid transparent", color: tab === "original" ? "var(--ink)" : "inherit" }}>Originalet · Original</button>
        <button onClick={() => setTab("tryck")} style={{ paddingBottom: 6, borderBottom: tab === "tryck" ? "1px solid var(--ink)" : "1px solid transparent", color: tab === "tryck" ? "var(--ink)" : "inherit" }}>Tryck · Print</button>
      </div>
      {tab === "original" && (
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 24, gap: 24 }}>
            <div>
              <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 8 }}>Unikt verk · One of one</div>
              <PriceLine work={work} />
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-soft)", maxWidth: "32ch", textAlign: "right", lineHeight: 1.5 }}>
              {sold ? "Detta verk är inte längre tillgängligt. Kontakta ateljén för att efterfråga liknande." : "Förfrågan öppnas i ett mejl med titel, mått och bild förifyllda."}
            </div>
          </div>
          {sold ? (
            <button className="btn primary" disabled style={{ width: "100%", padding: "18px 24px", opacity: 0.4, cursor: "not-allowed" }}>Inte tillgänglig · Not available</button>
          ) : (
            <a className="btn primary" href={inquireHref} style={{ width: "100%", padding: "18px 24px" }}>
              Förfråga om originalet · Inquire about the original<span className="arrow">→</span>
            </a>
          )}
          <p style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 12, letterSpacing: "0.06em" }}>Inramas på begäran. Frakt inom Sverige ingår. Internationell frakt offereras separat.</p>
        </div>
      )}
      {tab === "tryck" && (
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 20 }}>
            <div>
              <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 8 }}>Signerad upplaga · Signed edition · /50</div>
              <div className="serif" style={{ fontSize: 22 }}>{printPrices[size].toLocaleString("sv-SE")} <span style={{ fontSize: 12, fontFamily: "var(--sans)", letterSpacing: "0.12em", color: "var(--ink-soft)" }}>SEK</span></div>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-soft)" }}>{50 - 7} av 50 kvar</div>
          </div>
          <div style={{ display: "flex", gap: 8, marginBottom: 20 }}>
            {["A4", "A3", "A2"].map(s => (
              <button key={s} onClick={() => setSize(s)} style={{ flex: 1, padding: "14px 0", border: "1px solid", borderColor: size === s ? "var(--ink)" : "var(--rule)", background: size === s ? "var(--ink)" : "transparent", color: size === s ? "var(--paper)" : "var(--ink)", fontSize: 13, letterSpacing: "0.06em" }}>
                <div>{s}</div>
                <div style={{ fontSize: 10, opacity: 0.7, marginTop: 2 }}>{s === "A4" ? "21×30" : s === "A3" ? "30×42" : "42×59"} cm</div>
              </button>
            ))}
          </div>
          <button className="btn primary" style={{ width: "100%", padding: "18px 24px" }} onClick={()=>alert(`Tillagt: ${work.title_se} · ${size} · ${printPrices[size].toLocaleString('sv-SE')} SEK`)}>Lägg i varukorg · Add to cart <span className="arrow">→</span></button>
          <p style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 12, letterSpacing: "0.06em" }}>Hahnemühle bomullsark, 308 g/m². Signerad och numrerad. 7–10 dagars leverans.</p>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Nav, Footer, Paper, PriceLine, CommerceBlock, url, seriesUrl, workUrl });
