// sections.jsx — About, Focus, Projects, Articles, StatusLog, Contact, Footer
const { useState: useStateSec, useEffect: useEffectSec } = React;

// ── Shared settings fetch — one request, shared across Contact and Footer ──
const settingsPromise = fetch('/api/settings').then(r => r.json()).catch(() => ({}));

function useSettings() {
  const [s, setS] = useStateSec({});
  useEffectSec(() => { settingsPromise.then(setS); }, []);
  return s;
}

// consistent, chapter-numbered section header — single-author rhythm
function SectionHead({ ch, label, title, lead }) {
  return (
    <div className="sec-head">
      <div className="sec-meta">
        <span className="eyebrow chapter"><span className="ch">{ch}</span>{label}</span>
        <span className="sec-rule"></span>
      </div>
      <h2 className="sec-title">{title}</h2>
      {lead && <p className="sec-lead">{lead}</p>}
    </div>
  );
}

function About() {
  return (
    <section id="about" className="wrap reveal">
      <div className="about-grid">
        <div>
          <div className="sec-meta">
            <span className="eyebrow chapter"><span className="ch">01</span>about</span>
            <span className="sec-rule"></span>
          </div>
          <h2 className="sec-title">I make <span className="accent">order</span> from chaos.</h2>
          <div className="about-body">
            <p>I work in <strong>QA and automation</strong>, and I build tools and personal systems. I like taking a messy problem apart into clean, repeatable steps — then putting it back together so it actually makes sense.</p>
            <p>Most of my work lives at the seam between <strong>quality and engineering</strong>: writing tests that catch what matters, automating the boring and error-prone parts, and designing processes that still hold up six months later. I care less about clever and more about <strong>trustworthy</strong>.</p>
            <p>I also have a creative side. I think a lot about working <strong>sustainably</strong> — not burning out, and building systems that are kind to my own mind. A nerd who wants things to work, and the person behind them, too.</p>
            <div className="about-principles">
              <span className="principle"><i data-lucide="check"></i> test it before you trust it</span>
              <span className="principle"><i data-lucide="check"></i> automate the boring</span>
              <span className="principle"><i data-lucide="check"></i> sustainable &gt; heroic</span>
            </div>
          </div>
        </div>
        <div className="card about-card">
          <div className="ac-head">~/whoami</div>
          <div className="kv">
            <div className="row"><span className="k">role</span><span className="v">QA &amp; <b>automation</b></span></div>
            <div className="row"><span className="k">builds</span><span className="v"><b>SortiiiQ</b>, MyMoney</span></div>
            <div className="row"><span className="k">writes</span><span className="v">QA, systems, focus</span></div>
            <div className="row"><span className="k">thinks_about</span><span className="v">order from chaos</span></div>
            <div className="row"><span className="k">mind</span><span className="v"><b>focus-friendly</b>, sustainable</span></div>
            <div className="row"><span className="k">location</span><span className="v">Prague, CZ</span></div>
            <div className="row"><span className="k">status</span><span className="v">curious &amp; shipping</span></div>
          </div>
        </div>
      </div>
      <div className="about-lately">
        <div className="ll">// lately — where my focus goes</div>
        <div className="lately-grid">
          <div className="lately-item"><i data-lucide="git-branch"></i><span>Tuning <b>SortiiiQ</b> — the scanning &amp; classification pipeline.</span></div>
          <div className="lately-item"><i data-lucide="book-open"></i><span>Reading on <b>sustainable pace</b> &amp; burnout prevention in software.</span></div>
          <div className="lately-item"><i data-lucide="notebook-pen"></i><span>Building a <b>focus-friendly</b> note &amp; focus system of my own.</span></div>
        </div>
      </div>
    </section>
  );
}

const FOCUS = [
  { num: "01", icon: "bug", title: "Software Quality & QA", desc: "Testing strategy, critical thinking, and finding what breaks before a user ever does.", tags: ["testing", "strategy", "automation"] },
  { num: "02", icon: "terminal", title: "Tools & Projects", desc: "I build tools, experiments, and small systems that solve real problems — and I enjoy seeing them through.", tags: ["building", "experiments", "systems"] },
  { num: "03", icon: "brain-circuit", title: "Sustainable Work & Mind", desc: "Focus-friendly systems, burnout prevention, and working with my own mind — a sustainable pace over heroics.", tags: ["focus", "anti-burnout", "calm"] },
];

function Focus() {
  return (
    <section id="focus" className="wrap reveal">
      <SectionHead ch="02" label="focus"
        title="Three pillars I build on."
        lead="Technical depth, my own tools, and a healthy relationship with work — together they hold the whole thing up." />
      <div className="focus-grid">
        {FOCUS.map((f) => (
          <div key={f.title} className="card focus-card">
            <span className="num">{f.num}</span>
            <div className="focus-ico"><i data-lucide={f.icon}></i></div>
            <h3>{f.title}</h3>
            <p>{f.desc}</p>
            <div className="focus-tags">{f.tags.map((t) => <span key={t} className="mini-tag">{t}</span>)}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ── Projects — fetched from /api/projects ─────────────────────────────────
function Projects() {
  const [projects, setProjects] = useStateSec([]);

  useEffectSec(() => {
    fetch('/api/projects').then(r => r.json()).then(setProjects).catch(() => {});
  }, []);

  const STATUS = {
    active:   ['open source', ''],
    idea:     ['wip', 'wip'],
    archived: ['archived', 'archived'],
  };

  return (
    <section id="projects" className="wrap reveal">
      <SectionHead ch="03" label="selected projects"
        title="Things I've built."
        lead="Tools and systems, not a portfolio for show — each one tames a specific kind of chaos." />
      <div className="proj-grid">
        {projects.map((p, i) => {
          const [lbl, cls] = STATUS[p.status] || ['', ''];
          return (
            <a key={p.slug} href={'/projects/' + p.slug}
               className={'card proj-card' + (i === 0 ? ' featured' : '')}>
              <span className="glowedge"></span>
              <div className="proj-visual">
                <span className="proj-cap"><span className="dot"></span>{p.title.toLowerCase()}</span>
                <image-slot id={'proj-' + p.slug} shape="rect" fit="cover"
                  placeholder={'Drop a ' + p.title + ' screenshot'}></image-slot>
              </div>
              <div className="proj-body">
                <div className="proj-top">
                  <span className="proj-name">{p.title}</span>
                  <span className={'proj-status ' + cls}>{lbl}</span>
                </div>
                <p className="proj-desc">{p.shortDescription}</p>
                <div className="proj-foot">
                  <span className="proj-tags">
                    {(p.tags || '').split(',').filter(t => t.trim()).map(t => (
                      <span key={t.trim()} className="mini-tag">{t.trim()}</span>
                    ))}
                  </span>
                  <span className="proj-cta">read case study <i data-lucide="arrow-up-right"></i></span>
                </div>
              </div>
            </a>
          );
        })}
      </div>
    </section>
  );
}

// ── Articles — fetched from /api/notes ────────────────────────────────────
function Articles() {
  const [notes, setNotes] = useStateSec([]);
  const [active, setActive] = useStateSec('all');

  useEffectSec(() => {
    fetch('/api/notes').then(r => r.json()).then(setNotes).catch(() => {});
  }, []);

  const formatDate = (d) => {
    if (!d) return '';
    const [y, m] = d.split('-');
    return y + ' · ' + m;
  };

  const isCase = (n) => (n.category || '').toLowerCase().includes('case');

  const filters = ['all', ...[...new Set(
    notes.flatMap(n => [
      isCase(n) ? 'case' : null,
      ...(n.tags || '').split(',').map(t => t.trim()).filter(Boolean),
    ].filter(Boolean))
  )]];

  const shown = active === 'all' ? notes
    : notes.filter(n =>
        active === 'case'
          ? isCase(n)
          : (n.tags || '').split(',').map(t => t.trim()).includes(active)
      );

  return (
    <section id="articles" className="wrap reveal">
      <SectionHead ch="04" label="writing & case studies"
        title="Articles & case studies."
        lead="How I think, and what actually happened when I built it — testing, tools, systems, and a sustainable mind." />
      <div className="art-filters">
        {filters.map(f => (
          <button key={f} className={'filter-chip' + (active === f ? ' active' : '')}
            onClick={() => setActive(f)}>{f === 'case' ? 'case study' : f}</button>
        ))}
      </div>
      <div className="art-grid">
        {shown.map((n) => {
          const cs = isCase(n);
          const tags = (n.tags || '').split(',').map(t => t.trim()).filter(Boolean);
          if (n.wide) {
            return (
              <a key={n.slug} className="card art-card cs-wide" href={'/notes/' + n.slug}>
                <div className="cs-body">
                  <div className="art-top">
                    <span className="art-kind cs">case study</span>
                    <span className="art-date">{formatDate(n.publishedAt)}</span>
                  </div>
                  <h3>{n.title}</h3>
                  <p>{n.excerpt}</p>
                  <div className="art-foot cs-foot">
                    <span className="art-read"><i data-lucide="clock"></i> {n.readMinutes} min read</span>
                    <span className="art-arrow"><i data-lucide="arrow-up-right"></i></span>
                  </div>
                </div>
              </a>
            );
          }
          return (
            <a key={n.slug} className="card art-card" href={'/notes/' + n.slug}>
              <div className="art-top">
                <span className={'art-kind' + (cs ? ' cs' : '')}>{cs ? 'case study' : 'article'}</span>
                <span className="art-date">{formatDate(n.publishedAt)}</span>
              </div>
              <h3>{n.title}</h3>
              <p>{n.excerpt}</p>
              <div className="art-foot">
                <span className="art-tag">{tags[0]}</span>
                <span className="art-read"><i data-lucide="clock"></i> {n.readMinutes} min</span>
                <span className="art-arrow"><i data-lucide="arrow-up-right"></i></span>
              </div>
            </a>
          );
        })}
      </div>
    </section>
  );
}

// ── StatusLog — static live feed (no per-entry DB table yet) ──────────────
const STATUS_HEADLINE = "Heads-down on SortiiiQ — but reachable.";
const STATUS_LOG = [
  { t: "08:51", text: <>online. coffee <span className="hl">=&gt;</span> compiling.</> },
  { t: "09:37", text: <>triaging SortiiiQ tickets. one flaky test left.</> },
  { t: "10:14", text: <>found it: a race in the sort comparator. fix incoming.</> },
  { t: "11:29", text: <><span className="hl">142/142 green</span> — shipped, deploy clean.</> },
  { t: "12:40", text: <>lunch + a chapter on sustainable pace.</> },
  { t: "13:18", text: <>deep-work block: note-system schema. do not disturb.</> },
  { t: "14:22", text: <>surfacing for air — <span className="hl">open for questions</span>.</> },
];

function StatusLog() {
  const [clock, setClock] = useStateSec("");
  React.useEffect(() => {
    const tick = () => {
      const d = new Date();
      setClock(String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0"));
    };
    tick();
    const id = setInterval(tick, 15000);
    return () => clearInterval(id);
  }, []);
  return (
    <section id="status" className="wrap reveal">
      <SectionHead ch="05" label="status"
        title="Live from the desk."
        lead="A read-only log — what I'm doing right now, and whether I'm reachable. No likes, no noise. Just signal." />
      <div className="card statuslog">
        <div className="sl-bar">
          <span className="sl-title">~/status.log</span>
          <span className="sl-live"><span className="live-dot"></span> online · ready for questions <span className="sl-clock">{clock} local</span></span>
        </div>
        <div className="sl-status">
          <span className="sl-badge">STATUS</span>
          <span>{STATUS_HEADLINE}</span>
        </div>
        <div className="sl-feed">
          {STATUS_LOG.map((l, i) => (
            <div className="sl-line" key={i}><span className="t">[{l.t}]</span><span className="ar">›</span><span>{l.text}</span></div>
          ))}
          <div className="sl-line live"><span className="t">[{clock}]</span><span className="ar">›</span><span><span className="sl-cur"></span></span></div>
        </div>
        <div className="sl-foot">// read-only feed · reply at <a href="mailto:hi@sirucka.cz">hi@sirucka.cz</a></div>
      </div>
    </section>
  );
}

// ── Contact — email + social links from /api/settings ────────────────────
function Contact() {
  const s = useSettings();
  const email   = s.contactEmail  || 'hi@sirucka.cz';
  const github  = s.gitHubUrl     || '#';
  const mastodon= s.mastodonUrl   || '#';

  return (
    <section id="contact" className="wrap contact reveal">
      <div className="contact-inner">
        <SectionHead ch="06" label="contact"
          title={<>Let's bring <span className="accent">order</span> to some chaos.</>}
          lead="I write, test, automate, and build systems. Reach out — about QA, tooling, or just to talk about working sustainably in tech." />
        <div className="contact-links">
          <a className="btn btn-primary" href={'mailto:' + email}><i data-lucide="mail"></i> {email}</a>
          <a className="contact-link" href="#top"><img src="https://cdn.simpleicons.org/discord/A9B4D0" alt="" /> Discord</a>
          <a className="contact-link" href={github}><img src="https://cdn.simpleicons.org/github/A9B4D0" alt="" /> GitHub</a>
          <a className="contact-link" href={mastodon}><img src="https://cdn.simpleicons.org/mastodon/A9B4D0" alt="" /> Mastodon</a>
          <a className="contact-link" href="#top"><i data-lucide="rss"></i> RSS</a>
        </div>
      </div>
    </section>
  );
}

// ── Footer — email + social links from /api/settings ─────────────────────
function Footer() {
  const s = useSettings();
  const email   = s.contactEmail  || 'hi@sirucka.cz';
  const github  = s.gitHubUrl     || '#';
  const mastodon= s.mastodonUrl   || '#';

  const explore = [["about","#about"],["focus","#focus"],["projects","#projects"],["articles","#articles"],["status","#status"],["contact","#contact"]];
  return (
    <footer className="footer">
      <div className="wrap footer-grid">
        <div className="f-brand">
          <a className="brand" href="#top"><span className="mark">s/</span><span className="wm">sirucka<span className="cz">.cz</span></span></a>
          <p>QA, automation, and the systems around them. I build tools that bring order to chaos — and write about doing it sustainably.</p>
          <span className="f-status"><span className="live-dot"></span> online · ready for questions</span>
        </div>
        <div className="f-col">
          <h4>Explore</h4>
          <nav>{explore.map(([l, h]) => <a key={h} href={h}>{l}</a>)}</nav>
        </div>
        <div className="f-col">
          <h4>Elsewhere</h4>
          <nav>
            <a href={'mailto:' + email}><i data-lucide="mail"></i> {email}</a>
            <a href={github}><img src="https://cdn.simpleicons.org/github/A9B4D0" alt="" /> GitHub</a>
            <a href="#top"><img src="https://cdn.simpleicons.org/discord/A9B4D0" alt="" /> Discord</a>
            <a href={mastodon}><img src="https://cdn.simpleicons.org/mastodon/A9B4D0" alt="" /> Mastodon</a>
            <a href="#top"><i data-lucide="rss"></i> RSS</a>
          </nav>
        </div>
      </div>
      <div className="wrap footer-bottom">
        <span className="fbrand">sirucka<span className="cz">.cz</span></span>
        <span>// building order from chaos · © 2026 · may the tests be with you</span>
      </div>
    </footer>
  );
}

Object.assign(window, { About, Focus, Projects, Articles, StatusLog, Contact, Footer });
