// Blog — list page and full article view
// Hash routes: #/blog → list, #/blog/<slug> → article

function readBlogRouteFromHash() {
  const m = window.location.hash.match(/^#\/blog(\/([^/#?]+))?/);
  if (!m) return null;
  return m[2] ? { view: "post", slug: m[2] } : { view: "list" };
}

// ─── Content ────────────────────────────────────────────────────────────────

const BLOG_POSTS = [
  {
    id: "b1",
    slug: "5-razlogov-loncarstvo",
    category: "pottery",
    color: "tomato",
    title: {
      sl: "5 razlogov, zakaj preizkusiti lončarstvo",
      en: "5 reasons to try pottery",
    },
    excerpt: {
      sl: "Glina umiri um. Tukaj je pet razlogov, zakaj je lončarsko kolo idealno za odrasle začetnike — tudi če nisi nikoli prej delal z glino.",
      en: "Clay calms the mind. Here are five reasons the pottery wheel is ideal for adult beginners — even if you've never touched clay before.",
    },
    author: "Ana K.",
    authorBio: {
      sl: "Ana vodi Studio Krog v Šiški skupaj z Miho. Lončarstvo poučuje že 12 let.",
      en: "Ana runs Studio Krog in Šiška together with Miha. She has been teaching pottery for 12 years.",
    },
    date: "14. apr 2026",
    readMin: 5,
    sections: [
      {
        type: "lede",
        sl: "Smo sredi pomladi in Ljubljana je spet polna tečajev in delavnic. Vsako leto se nam pri Studio Krog pridruži na ducate odraslih, ki lončarstva nikoli niso preizkusili — in vsako leto nas znova preseneti, kako hitro se zaljubijo vanj. Tukaj je pet razlogov, zakaj je lončarstvo vredna izkušnja, ne glede na to, ali si začetnik ali izkušen ustvarjalec.",
        en: "Spring is here and Ljubljana is full of courses and workshops again. Every year, dozens of adults who have never tried pottery join us at Studio Krog — and every year it surprises us how quickly they fall in love with it. Here are five reasons pottery is a worthwhile experience, whether you're a complete beginner or a seasoned maker.",
      },
      {
        type: "h2",
        sl: "1. Umiri um in telo",
        en: "1. It calms your mind and body",
      },
      {
        type: "p",
        sl: "Ko roki potopita v glino in začneta oblikovati, se um prisiljen umiri. Centrifugalna sila vretena zahteva vso tvojo pozornost — ni prostora za misli o delu, elektronski pošti ali vikend načrtih. Znanstveniki to imenujejo \"flow stanje\", lončarji pa temu preprosto rečemo glina. V delavnicah pogosto opazimo, da udeleženci prihajajo napeti in odhajajo umirjeni — samo od tega, ker so dve ali tri ure delali z rokami.",
        en: "When your hands sink into clay and begin to shape it, the mind is forced to quieten. The centrifugal force of the wheel demands your full attention — there's no room for thoughts about work, emails or weekend plans. Scientists call it a \"flow state\"; potters simply call it clay. In workshops we often notice participants arriving tense and leaving calm — just from spending two or three hours working with their hands.",
      },
      {
        type: "quote",
        sl: "\"Prvič v življenju sem šla domov po delovnem dnevu brez glavobola. Glina je edina stvar, ki je res deluje.\"",
        en: "\"For the first time in my life I went home after a working day without a headache. Clay is the only thing that actually works.\"",
        attribution: { sl: "udeleženka delavnice, Ljubljana 2025", en: "workshop participant, Ljubljana 2025" },
      },
      {
        type: "h2",
        sl: "2. V treh urah imaš skodelico",
        en: "2. In three hours you have a cup",
      },
      {
        type: "p",
        sl: "Ena največjih frustracij pri učenju novih spretnosti je, da dolgo ne vidiš oprijemljivih rezultatov. Lončarstvo je drugačno. Na začetniški delavnici se v eni popoldanski sesiji naučiš osnov centriranja gline in dviganja stene — in ob koncu imaš v roki svojo prvo skodelico. Ni popolna, a je tvoja. Po dveh tednih jo žgemo, glaziramo in vrneš domov z delujočo posodo, ki jo boš vsako jutro polnil s kavo.",
        en: "One of the biggest frustrations in learning a new skill is that you don't see tangible results for a long time. Pottery is different. In a single afternoon session at a beginners' workshop you learn the basics of centring clay and pulling up the wall — and at the end you hold your first cup. It's not perfect, but it's yours. Two weeks later we fire and glaze it, and you come home with a working vessel you'll fill with coffee every morning.",
      },
      {
        type: "h2",
        sl: "3. Je socialna izkušnja",
        en: "3. It's a social experience",
      },
      {
        type: "p",
        sl: "Lončarska delavnica ni tihota terapevtske sobe. Je glasen, moder prostor, kjer delajo hkrati štiri do osem ljudi, kjer se smejite drug drugemu, ko glinena stena zruši, in kjer si delite nasvete. V naši skupini se v vsakem tečaju spletejo prava prijateljstva — nekaterim so delavnice postale tedenska socialna rutina, ki jo ne bi zamenjali za nič. Če si nov v mestu ali iščeš skupnost, je atelje odlično izhodišče.",
        en: "A pottery workshop isn't the silence of a therapy room. It's a loud, blue-smeared space where four to eight people work at the same time, where you laugh at each other when the clay wall collapses, and where you share tips. Real friendships form in every course we run — for some participants the workshops have become a weekly social ritual they wouldn't trade for anything. If you're new in town or looking for a community, a studio is a great starting point.",
      },
      {
        type: "h2",
        sl: "4. Odneseš domov nekaj trajnega",
        en: "4. You take something lasting home",
      },
      {
        type: "p",
        sl: "V primerjavi z večino tečajev — ki ti pustijo le znanje in morda certifikat — lončarstvo prinese oprijemljive rezultate. Vsak udeleženec odnese domov med eno in tremi glaziranimi posodami, ki jih je naredil z lastnimi rokami. Skodelice, sklede, vazo. Predmeti, ki jih boš vsak dan videl v kuhinji in se spomnil tistega popoldneva. Mnogi se vrnejo prav zato: ker želijo ustvariti celoten komplet posode.",
        en: "Compared to most courses — which leave you with knowledge and perhaps a certificate — pottery delivers tangible results. Every participant takes home between one and three glazed pieces made with their own hands. Cups, bowls, a vase. Objects you'll see in the kitchen every day and be reminded of that afternoon. Many come back for exactly this reason: they want to make an entire set of crockery.",
      },
      {
        type: "h2",
        sl: "5. Nima starostne meje",
        en: "5. There's no age limit",
      },
      {
        type: "p",
        sl: "K nam hodijo šestletniki z mamami, dijaki, podjetniki po petdesetem in upokojenci. Glina je nevtralna — ne zanima je, ali si koordiniran ali ne, ali si kdaj ustvarjal ali ne. Zahteva le prisotnost in potrpežljivost. Fizično je primerna skoraj za vsakogar: delamo sede, pritisk je na rokah, ne na hrbtu. Edina prava predpostavka je, da si pripravljen imeti umazane roke.",
        en: "We have six-year-olds with their mums, teenagers, fifty-something executives and retired teachers. Clay is neutral — it doesn't care whether you're coordinated or not, whether you've ever made anything or not. It only asks for presence and patience. Physically it suits almost everyone: you work seated, the pressure is in your hands not your back. The only real prerequisite is being willing to get your hands dirty.",
      },
      {
        type: "h2",
        sl: "Kje začeti v Ljubljani?",
        en: "Where to start in Ljubljana?",
      },
      {
        type: "p",
        sl: "V Ljubljani deluje več lončarskih ateljejev. Studio Krog v Šiški ponuja enkratne začetniške delavnice ob sobotah in nedeljah, pa tudi večerne tečaje za tiste, ki bi radi napredovali. Cena začetniške delavnice je 65 €, vključno z materialom in žganjem. Rezervacijo opravi na spletni strani — mesta gredo hitro.",
        en: "Ljubljana has several pottery studios. Studio Krog in Šiška offers one-off beginner workshops on Saturdays and Sundays, as well as evening courses for those who want to progress. The beginner workshop costs €65, including materials and firing. Book on their website — spots go quickly.",
      },
      {
        type: "cta",
        sl: "Poglej delavnice Studio Krog →",
        en: "Browse Studio Krog workshops →",
        action: "pottery",
      },
    ],
  },
  {
    id: "b2",
    slug: "plenar-slikanje-na-prostem",
    category: "painting",
    color: "cobalt",
    title: {
      sl: "Plenér: slikanje na prostem za vsakogar",
      en: "Plein air: outdoor painting for everyone",
    },
    excerpt: {
      sl: "Zakaj slikarji vedno znova zapuščajo atelje in gredo ven? Odgovor je v svetlobi, spontanosti in dišečem zraku.",
      en: "Why do painters keep leaving the studio to go outside? The answer lies in light, spontaneity, and fresh air.",
    },
    author: "Marjetica K.",
    authorBio: {
      sl: "Marjetica Kos je akademska slikarka z razstavami v MGLC in Cankarjevem domu. Vodi Atelje Marjetica v Mariboru.",
      en: "Marjetica Kos is an academic painter with exhibitions at MGLC and Cankarjev dom. She runs Atelje Marjetica in Maribor.",
    },
    date: "8. apr 2026",
    readMin: 6,
    sections: [
      {
        type: "lede",
        sl: "Ko Francozi govorijo o plenéru, mislijo na tradicijo impressionistov, ki so v 19. stoletju prvič odnesli platno ven. Ko mi govorimo o njem, mislimo na Ptujski Likovni Krožek, ki vsako soboto ob devetih zjutraj postavi stative ob gradu in reki Dravi. Plenér je demokratičen: za začetek ne potrebuješ nič več kot skicirko in svinčnik.",
        en: "When the French speak of plein air, they mean the tradition of the Impressionists, who in the 19th century first took their canvases outside. When we speak of it, we mean the Ptujski Likovni Krožek, which every Saturday at nine in the morning sets up easels beside the castle and the River Drava. Plein air is democratic: to start you need nothing more than a sketchbook and a pencil.",
      },
      {
        type: "h2",
        sl: "Zakaj je naravna svetloba drugačna",
        en: "Why natural light is different",
      },
      {
        type: "p",
        sl: "V ateljeju je svetloba statična — ker jo tako želiš. Na prostem se vsako minuto premika. To je izziv, ki te sili v hitrost in odločnost. Impresionisti so razvili kratke, energične poteze prav zato, ker niso imeli časa za premislek — oblak se je premaknil in svetloba je bila drugačna. Ravno ta prisila ustvari drugačno kakovost slike: bolj živo, bolj spontano, manj izlizan.",
        en: "In the studio light is static — because you want it that way. Outside it shifts every minute. This challenge forces you towards speed and decisiveness. The Impressionists developed short, energetic strokes precisely because they had no time to think — a cloud moved and the light changed. This very constraint creates a different quality of painting: more alive, more spontaneous, less overworked.",
      },
    ],
  },
  {
    id: "b3",
    slug: "pihanje-stekla-mit-in-resnica",
    category: "glass",
    color: "sage",
    title: {
      sl: "Pihanje stekla: mit in resnica",
      en: "Glass blowing: myth vs. reality",
    },
    excerpt: {
      sl: "Mnogi mislijo, da je pihanje stekla nevarno in dostopno samo za izkušene. Rogaška Glass Lab dokazuje nasprotno.",
      en: "Many think glass blowing is dangerous and only for the experienced. Rogaška Glass Lab proves otherwise.",
    },
    author: "Rogaška GL",
    authorBio: {
      sl: "Rogaška Glass Lab deluje ob stari steklarni v Rogaški Slatini. Mojstri z več kot 25 leti prakse.",
      en: "Rogaška Glass Lab operates next to the historic glassworks in Rogaška Slatina. Masters with over 25 years of practice.",
    },
    date: "2. apr 2026",
    readMin: 5,
    sections: [
      {
        type: "lede",
        sl: "Steklo pri 1100°C. Dolga jeklena cev. Pol sekunde za odločitev, kako pihati. Zveni zastrašujoče — in na to računamo, ko vas povabimo v delavnico. Ker tisto, kar sledi, je med najlepšimi izkušnjami, ki jih ponujamo.",
        en: "Glass at 1100°C. A long steel blowpipe. Half a second to decide how to blow. It sounds intimidating — and we count on that when we invite you into the workshop. Because what follows is among the finest experiences we offer.",
      },
      {
        type: "h2",
        sl: "Mit: je nevarno",
        en: "Myth: it's dangerous",
      },
      {
        type: "p",
        sl: "Steklo je res vroče. Toda v delavnici nikoli ne stojiš sam. Mojster je z vami ves čas, vodi vsak korak, drži cev, kadar je to potrebno. V 25 letih delavnic pri nas ni bilo nobene resne poškodbe. Varnost je del rokodelske tradicije, ki jo prenašamo naprej.",
        en: "Glass is indeed hot. But in the workshop you're never standing alone. The master is with you at every step, guiding every move, holding the pipe when needed. In 25 years of workshops we have had no serious injuries. Safety is part of the craft tradition we pass on.",
      },
    ],
  },
  {
    id: "b4",
    slug: "tkanje-ob-bledu",
    category: "textile",
    color: "mustard",
    title: {
      sl: "Tkanje ob Bledu: počasno življenje",
      en: "Weaving by Bled: slow living",
    },
    excerpt: {
      sl: "Statve iz 1920 v koči ob jezeru. Pogovor z mojstrico Meto Gornik o tradiciji in pomirjujoči moči volne.",
      en: "A 1920s loom in a lakeside cottage. A conversation with weaving master Meta Gornik on tradition and the calming power of wool.",
    },
    author: "Meta G.",
    authorBio: {
      sl: "Meta Gornik vodi Statve Bled, eno najstarejših aktivnih tkalnc v Sloveniji.",
      en: "Meta Gornik runs Statve Bled, one of the oldest active weaving studios in Slovenia.",
    },
    date: "28. mar 2026",
    readMin: 7,
    sections: [
      {
        type: "lede",
        sl: "Ko vstopite v Statve Bled, vas najprej prevzame vonj: čista volna, les in malo lanenega olja. Statve, na katerih boste delali, so iz leta 1920 — isto leto, ko je bila ustanovljena Republika Slovenija. Meta Gornik jih je podedovala od babice in jim vrne življenje vsako soboto.",
        en: "When you enter Statve Bled, the smell hits you first: clean wool, wood and a little linseed oil. The loom you'll be working on dates from 1920 — the same year the Republic of Slovenia was established. Meta Gornik inherited it from her grandmother and brings it back to life every Saturday.",
      },
      {
        type: "h2",
        sl: "Počasnost kot namen",
        en: "Slowness as intention",
      },
      {
        type: "p",
        sl: "Tkanje ne dopušča hitenja. Vsaka nit gre skozi luknjico posebej. En šal zahteva tri do štiri ure pozorne, ponavljajoče se geste — levi, desni, levi, desni. Ta ritem je točno to, kar iščejo udeleženci: odklop od zaslonov, od hitrosti, od nenehnih odločitev. \"Tkanje me reši pred pregorjevanjem,\" pravi Meta. \"Ko sedem za statve, mi ni treba biti nihče drug.\"",
        en: "Weaving does not allow hurrying. Each thread passes through its heddle one by one. A single scarf requires three to four hours of careful, repetitive gesture — left, right, left, right. This rhythm is exactly what participants are looking for: disconnection from screens, from speed, from constant decision-making. \"Weaving saves me from burnout,\" says Meta. \"When I sit at the loom, I don't have to be anyone else.\"",
      },
    ],
  },
];

// ─── Helpers ────────────────────────────────────────────────────────────────

function BlogCoverSvg({ post, wide }) {
  const h = wide ? 320 : 220;
  return (
    <div className={`cover-${post.color}`} style={{ width: "100%", height: h }}>
      <svg width="100%" height={h} viewBox={`0 0 640 ${h}`} preserveAspectRatio="xMidYMid slice"
           style={{ display:"block" }}>
        <defs>
          <linearGradient id={`g-${post.id}`} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0" stopColor="currentColor" stopOpacity="0.28"/>
            <stop offset="1" stopColor="currentColor" stopOpacity="0.06"/>
          </linearGradient>
        </defs>
        <rect width="640" height={h} fill={`url(#g-${post.id})`}/>
        <text x="24" y={h - 16} fontSize="11" fontFamily="var(--font-mono)" fill="currentColor"
              opacity="0.55" letterSpacing="1.5">
          {post.author.toUpperCase()} · {post.date.toUpperCase()}
        </text>
      </svg>
    </div>
  );
}

// ─── Blog List Page ──────────────────────────────────────────────────────────

function BlogListPage({ lang, onBack, onOpenPost }) {
  const t  = useT();
  const sl = lang === "sl";
  const featured = BLOG_POSTS[0];
  const rest     = BLOG_POSTS.slice(1);

  return (
    <div className="blog-page-wrap">
      <button type="button" className="host-back mono tiny" onClick={onBack}>
        ← {t.staticBackHome}
      </button>

      {/* Page header */}
      <div className="blog-page-header">
        <span className="blog-page-badge mono tiny">
          {sl ? "✏ BLOG · ČLANKI" : "✏ BLOG · ARTICLES"}
        </span>
        <h1 className="blog-page-title">
          {sl ? "Iz sveta\nlikovnih delavnic." : "From the world\nof art workshops."}
        </h1>
        <p className="blog-page-sub">
          {sl
            ? "Nasveti, zgodbe in intervjuji z izvajalci, ki delajo z rokami."
            : "Tips, stories and interviews from makers who work with their hands."}
        </p>
      </div>

      {/* Featured post */}
      <article className="blog-featured" onClick={() => onOpenPost(featured.slug)}>
        <div className="blog-featured-cover">
          <BlogCoverSvg post={featured} wide />
        </div>
        <div className="blog-featured-body">
          <div className="blog-featured-meta">
            <span className={`pill accent-${featured.color}`}>
              {(window.CATEGORIES || []).find(c => c.id === featured.category)?.[lang === "en" ? "en" : "label"] || featured.category}
            </span>
            <span className="mono tiny muted">{featured.readMin} min · {featured.date}</span>
          </div>
          <h2 className="blog-featured-title">
            {sl ? featured.title.sl : featured.title.en}
          </h2>
          <p className="blog-featured-excerpt">
            {sl ? featured.excerpt.sl : featured.excerpt.en}
          </p>
          <div className="blog-featured-foot">
            <span className="mono tiny muted">{featured.author}</span>
            <span className="blog-read-link mono tiny">{sl ? "Beri →" : "Read →"}</span>
          </div>
        </div>
      </article>

      {/* Grid */}
      <div className="blog-list-grid">
        {rest.map(post => (
          <article key={post.id} className={`blog-list-card card accent-${post.color}`}
                   onClick={() => onOpenPost(post.slug)}>
            <div className="blog-list-cover">
              <BlogCoverSvg post={post} />
            </div>
            <div className="grid-body">
              <div className="grid-top">
                <span className={`pill accent-${post.color}`}>
                  {(window.CATEGORIES || []).find(c => c.id === post.category)?.[lang === "en" ? "en" : "label"] || post.category}
                </span>
                <span className="mono tiny muted">{post.readMin} min</span>
              </div>
              <h3 className="grid-title">{sl ? post.title.sl : post.title.en}</h3>
              <p className="blog-list-excerpt">
                {sl ? post.excerpt.sl : post.excerpt.en}
              </p>
              <div className="grid-footer">
                <span className="mono tiny muted">{post.author} · {post.date}</span>
                <span className="blog-read-link mono tiny">{sl ? "Beri →" : "Read →"}</span>
              </div>
            </div>
          </article>
        ))}
      </div>
    </div>
  );
}

// ─── Blog Post Page ──────────────────────────────────────────────────────────

function BlogPostPage({ slug, lang, onBack, onOpenWorkshopsCategory }) {
  const t    = useT();
  const sl   = lang === "sl";
  const post = BLOG_POSTS.find(p => p.slug === slug);

  if (!post) {
    return (
      <div className="blog-page-wrap">
        <button type="button" className="host-back mono tiny" onClick={onBack}>← {t.staticBackHome}</button>
        <p className="mono tiny muted" style={{ marginTop: "32px" }}>{sl ? "Prispevek ne obstaja." : "Post not found."}</p>
      </div>
    );
  }

  const catLabel = (window.CATEGORIES || []).find(c => c.id === post.category)?.[sl ? "label" : "en"] || post.category;

  return (
    <div className="blog-page-wrap">
      {/* Back */}
      <button type="button" className="host-back mono tiny" onClick={onBack}>
        ← {sl ? "Blog" : "Blog"}
      </button>

      {/* Article hero */}
      <div className={`blog-post-hero accent-${post.color}`}>
        <div className="blog-post-hero-inner">
          <div className="blog-post-hero-meta">
            <span className={`pill accent-${post.color}`}>{catLabel}</span>
            <span className="mono tiny" style={{ opacity: 0.6 }}>{post.readMin} min · {post.date}</span>
          </div>
          <h1 className="blog-post-title">
            {sl ? post.title.sl : post.title.en}
          </h1>
          <div className="blog-post-byline">
            <div className={`avatar avatar-${post.color}`} style={{ width: 36, height: 36, fontSize: 16 }}>
              {post.author[0]}
            </div>
            <div>
              <div className="blog-post-author">{post.author}</div>
              <div className="mono tiny muted">{sl ? post.authorBio.sl : post.authorBio.en}</div>
            </div>
          </div>
        </div>
        <div className="blog-post-hero-visual">
          <BlogCoverSvg post={post} wide />
        </div>
      </div>

      {/* Article body */}
      <article className="blog-post-article">
        {post.sections.map((sec, i) => {
          if (sec.type === "lede") {
            return <p key={i} className="blog-post-lede">{sl ? sec.sl : sec.en}</p>;
          }
          if (sec.type === "h2") {
            return <h2 key={i} className="blog-post-h2">{sl ? sec.sl : sec.en}</h2>;
          }
          if (sec.type === "p") {
            return <p key={i} className="blog-post-p">{sl ? sec.sl : sec.en}</p>;
          }
          if (sec.type === "quote") {
            return (
              <blockquote key={i} className="blog-post-quote">
                <p>{sl ? sec.sl : sec.en}</p>
                {sec.attribution && (
                  <footer className="mono tiny muted">— {sl ? sec.attribution.sl : sec.attribution.en}</footer>
                )}
              </blockquote>
            );
          }
          if (sec.type === "cta") {
            return (
              <div key={i} className="blog-post-cta">
                <button
                  type="button"
                  className="btn-primary"
                  onClick={() => onOpenWorkshopsCategory && onOpenWorkshopsCategory(sec.action)}
                >
                  {sl ? sec.sl : sec.en}
                </button>
              </div>
            );
          }
          return null;
        })}
      </article>

      {/* Related posts */}
      {BLOG_POSTS.filter(p => p.slug !== slug).length > 0 && (
        <section className="blog-related">
          <div className="section-label mono tiny">{sl ? "PREBERITE ŠE" : "MORE ARTICLES"}</div>
          <div className="blog-related-grid">
            {BLOG_POSTS.filter(p => p.slug !== slug).slice(0, 3).map(related => (
              <article key={related.id} className={`blog-list-card card accent-${related.color}`}
                       onClick={() => {
                         window.location.hash = `#/blog/${related.slug}`;
                         window.scrollTo(0, 0);
                       }}>
                <div className="blog-list-cover">
                  <BlogCoverSvg post={related} />
                </div>
                <div className="grid-body">
                  <div className="grid-top">
                    <span className={`pill accent-${related.color}`}>
                      {(window.CATEGORIES || []).find(c => c.id === related.category)?.[sl ? "label" : "en"] || related.category}
                    </span>
                    <span className="mono tiny muted">{related.readMin} min</span>
                  </div>
                  <h3 className="grid-title">{sl ? related.title.sl : related.title.en}</h3>
                  <div className="grid-footer">
                    <span className="mono tiny muted">{related.author}</span>
                    <span className="blog-read-link mono tiny">{sl ? "Beri →" : "Read →"}</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { readBlogRouteFromHash, BLOG_POSTS, BlogListPage, BlogPostPage });
