// Reaksiyoner — Republik-style teaser components

// --- Helpers ---
function initials(name) {
  return name.split(" ").map(s => s[0]).join("").slice(0, 2).toUpperCase();
}

// Cover placeholder — striped SVG with monospace caption (fallback),
// OR real image background when `src` is provided.
function CoverPlaceholder({ src, label, tone = 1, aspect = "16/9", className = "", style = {} }) {
  const tones = {
    1: { bg: "#2a2825", fg: "#3a3631", text: "#a89e8d" }, // ink
    2: { bg: "#a3623f", fg: "#b06b46", text: "#f3eee5" }, // terracotta
    3: { bg: "#d9d0c1", fg: "#cdc3b2", text: "#3a3631" }, // paper
    4: { bg: "#1a2a3a", fg: "#243648", text: "#cdd5dd" }, // navy
  };
  const t = tones[tone] || tones[1];
  const id = `stripe-${Math.random().toString(36).slice(2, 8)}`;

  // --- Path A: real image cover ---
  if (src) {
    return (
      <div className={`cover ${className}`} style={{
        width: "100%",
        aspectRatio: aspect,
        background: t.bg,
        backgroundImage: `url("${src}")`,
        backgroundSize: "cover",
        backgroundPosition: "center",
        position: "relative",
        ...style,
      }}>
        {/* subtle film grain / darken to keep text legible when used as a hero */}
        <div style={{
          position: "absolute", inset: 0,
          background: "linear-gradient(180deg, rgba(0,0,0,0) 40%, rgba(0,0,0,0.25) 100%)",
          pointerEvents: "none",
        }} />
      </div>
    );
  }

  // --- Path B: typographic striped placeholder (Republik-style) ---
  return (
    <div className={`cover ${className}`} style={{
      width: "100%",
      aspectRatio: aspect,
      background: t.bg,
      ...style,
    }}>
      <svg width="100%" height="100%" preserveAspectRatio="none"
           viewBox="0 0 400 300" style={{ position: "absolute", inset: 0, display: "block" }}>
        <defs>
          <pattern id={id} patternUnits="userSpaceOnUse" width="14" height="14"
                   patternTransform="rotate(-28)">
            <rect width="14" height="14" fill={t.bg} />
            <rect width="7" height="14" fill={t.fg} opacity="0.55" />
          </pattern>
        </defs>
        <rect width="400" height="300" fill={`url(#${id})`} />
        <rect width="400" height="300" fill={t.bg} opacity="0.28" />
      </svg>
      {label && (
        <div className="cover-cap" style={{ color: t.text }}>
          foto · {label}
        </div>
      )}
    </div>
  );
}

// --- Header ---
function Header({ route, onNav }) {
  const navItems = [
    { id: "home",    label: "Magazin" },
    { id: "feed",    label: "Akış" },
    { id: "dialog",  label: "Diyalog" },
    { id: "search",  label: "Ara" },
  ];
  return (
    <header className="masthead">
      <div className="mast-top">
        <button className="mast-icon mast-icon-left" aria-label="Menü" title="Menü">
          {/* Hamburger / book glyph */}
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M3 6h18M3 12h18M3 18h18" />
          </svg>
        </button>
        <a href="#" className="wordmark" onClick={(e) => { e.preventDefault(); onNav({ view: "home" }); }} aria-label="Reaksiyoner anasayfa">
          <span className="wmtxt">Reaksiyoner</span>
        </a>
        <button className="mast-icon mast-icon-right" aria-label="Ara">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
            <circle cx="11" cy="11" r="7" />
            <path d="m20 20-3.5-3.5" />
          </svg>
        </button>
      </div>
      <nav className="mast-nav">
        {navItems.map(n => (
          <button
            key={n.id}
            className={`navlink ${route.view === n.id ? "is-active" : ""}`}
            onClick={() => onNav({ view: n.id })}
          >
            {n.label}
          </button>
        ))}
      </nav>
    </header>
  );
}

// --- Issue band ---
function IssueBand() {
  return (
    <div className="issue-band">
      <div className="issue-eyebrow">Sayı 412 · Çarşamba, 20 Mayıs 2026</div>
      <h1 className="issue-title">
        Pasifik mutabakatı, Anadolu'nun yeni göç haritası ve Türkçe-merkezli açık bir modelin doğuşu. Birlikte okuyalım.
      </h1>
      <div className="issue-edits">Yayın yönetmeni: Burcu Sertoğlu · Görsel yönetmen: Hakan Akar</div>
    </div>
  );
}

// --- Section heading ---
function SectionHead({ title, note }) {
  return (
    <div className="section-head">
      <h2 className="sh-title">{title}</h2>
      {note && <div className="sh-note">{note}</div>}
    </div>
  );
}

// --- Byline shared ---
function Byline({ writer, date, readMin, color, withRole = true }) {
  return (
    <p className="t-byline" style={{ color }}>
      <span>Yazan </span>
      <span className="by-name">{writer.name}</span>
      {withRole && <em>, {writer.role}</em>}
      {date && <em>{` · ${date}`}</em>}
      {readMin && <em>{` · ${readMin} dakika`}</em>}
    </p>
  );
}

// --- Format label ---
function FormatLabel({ fmt, color }) {
  const f = FORMATS[fmt];
  if (!f) return null;
  // Republik shows the format label in the format's brand color (formatColor), even on colored bg.
  // But on dark backgrounds we soften to the text color.
  return (
    <p className="t-format" style={{ color: color || f.color }}>
      {f.label}
    </p>
  );
}

// ============================================================
// TEASER TYPES
// ============================================================

// --- Typo teaser (text-only, full-width band of solid color) ---
function TypoTeaser({ teaser, onOpen }) {
  const art = ARTICLES[teaser.ref];
  const writer = WRITERS[art.writer];
  return (
    <section
      className={`teaser t-typo ${teaser.closing ? "closing" : ""}`}
      style={{ background: teaser.bgColor, color: teaser.color }}
      onClick={() => onOpen(art.id)}
    >
      <div className="t-typo-inner">
        <FormatLabel fmt={art.fmt} color={teaser.accent || teaser.color} />
        <h2 className={`t-title size-${teaser.titleSize || "default"}`}>{art.title}</h2>
        <p className="t-lead">{art.lead}</p>
        <Byline writer={writer} readMin={art.readMin} color={teaser.color} />
      </div>
    </section>
  );
}

// --- Image teaser (full-bleed image bg w/ overlaid text) ---
function ImageTeaser({ teaser, onOpen }) {
  const art = ARTICLES[teaser.ref];
  const writer = WRITERS[art.writer];
  const [posY, posX] = posFromPosition(teaser.textPosition || "bottomleft");
  return (
    <section
      className="teaser t-image-wrap"
      style={{
        background: teaser.bgColor,
        color: teaser.color,
        "--pos-x": posX,
        "--pos-y": posY,
      }}
      onClick={() => onOpen(art.id)}
    >
      <div className="t-image-bg">
        <CoverPlaceholder
          src={teaser.image?.src || art.cover}
          label={teaser.image?.label || art.imageLabel}
          tone={teaser.image?.tone || 1}
          aspect="auto"
          style={{ height: "100%" }}
        />
        {/* Dark gradient overlay for legibility */}
        <div style={{
          position: "absolute", inset: 0,
          background: teaser.color === "#ffffff" || teaser.color === "#f6efe3"
            ? "linear-gradient(to top, rgba(0,0,0,0.35), rgba(0,0,0,0.1) 50%, rgba(0,0,0,0.0))"
            : "linear-gradient(to top, rgba(255,255,255,0.25), rgba(255,255,255,0.0))"
        }} />
      </div>
      <div className="t-image-text">
        <div className="t-image-text-cell">
          <FormatLabel fmt={art.fmt} color={teaser.color} />
          <h2 className={`t-title size-${teaser.titleSize || "default"}`}>{art.title}</h2>
          <p className="t-lead">{art.lead}</p>
          <Byline writer={writer} readMin={art.readMin} color={teaser.color} />
        </div>
      </div>
      {teaser.byline && <div className="t-image-byline">{teaser.byline}</div>}
    </section>
  );
}

function posFromPosition(pos) {
  // returns [posY (start/center/end), posX (start/center/end)]
  const map = {
    topleft:     ["start", "start"],
    topright:    ["start", "end"],
    bottomleft:  ["end", "start"],
    bottomright: ["end", "end"],
    top:         ["start", "center"],
    middle:      ["center", "center"],
    bottom:      ["end", "center"],
  };
  return map[pos] || ["end", "start"];
}

// --- Split teaser (image + text side-by-side) ---
function SplitTeaser({ teaser, onOpen }) {
  const art = ARTICLES[teaser.ref];
  const writer = WRITERS[art.writer];
  return (
    <section
      className={`teaser t-split ${teaser.reverse ? "reverse" : ""}`}
      style={{ background: teaser.bgColor, color: teaser.color }}
      onClick={() => onOpen(art.id)}
    >
      <div className="t-split-inner">
        <div className="t-split-image">
          <CoverPlaceholder
            src={teaser.image?.src || art.cover}
            label={teaser.image?.label || art.imageLabel}
            tone={teaser.image?.tone || 1}
            aspect="4/3"
          />
        </div>
        <div className="t-split-content">
          <FormatLabel fmt={art.fmt} color={teaser.color} />
          <h2 className="t-title size-default">{art.title}</h2>
          <p className="t-lead">{art.lead}</p>
          <Byline writer={writer} readMin={art.readMin} color={teaser.color} />
        </div>
      </div>
    </section>
  );
}

// --- Tile (used in TileRow) ---
function Tile({ tile, onOpen }) {
  const art = ARTICLES[tile.ref];
  const writer = WRITERS[art.writer];
  return (
    <div
      className="t-tile"
      style={{ background: tile.bgColor, color: tile.color }}
      onClick={() => onOpen(art.id)}
    >
      {tile.image && (
        <div className="t-tile-image">
          <CoverPlaceholder
            src={tile.image.src || art.cover}
            label={tile.image.label || art.imageLabel}
            tone={tile.image.tone || 1}
            aspect="1/1"
          />
        </div>
      )}
      <div className="t-tile-text">
        <FormatLabel fmt={art.fmt} color={tile.color} />
        <h3 className="t-title">{art.title}</h3>
        <p className="t-lead">{art.lead}</p>
        <div className="t-tile-byline">
          <span style={{ fontWeight: 500 }}>{writer.name}</span>
          <span style={{ opacity: 0.7 }}> · {art.readMin} dakika</span>
        </div>
      </div>
    </div>
  );
}

// --- TileRow (group of 2 or 3 tiles) ---
function TileRow({ teaser, onOpen }) {
  return (
    <div className={`tile-row cols-${teaser.columns || 2}`}>
      {teaser.tiles.map((tile, i) => <Tile key={i} tile={tile} onOpen={onOpen} />)}
    </div>
  );
}

// --- Briefing teaser ("Bu hafta önemli olanlar") ---
function BriefingTeaser({ teaser, onOpen }) {
  const art = ARTICLES[teaser.ref];
  const writer = WRITERS[art.writer];
  return (
    <section
      className="teaser t-briefing"
      style={{ background: teaser.bgColor, color: teaser.color }}
      onClick={() => onOpen(art.id)}
    >
      <div className="t-briefing-inner">
        <FormatLabel fmt={art.fmt} color={teaser.color} />
        <h2 className="t-title">{art.title}</h2>
        <p className="t-lead">{art.lead}</p>
        <div className="brief-items">
          {teaser.items.map((it, i) => {
            const a = ARTICLES[it.ref];
            if (!a) return null;
            const f = FORMATS[a.fmt];
            return (
              <div key={i} className="brief-item" onClick={(e) => { e.stopPropagation(); onOpen(a.id); }}>
                <div className="bi-date">{it.date}</div>
                <div>
                  <div className="bi-fmt" style={{ color: f.color }}>{f.label}</div>
                  <h4 className="bi-title">{a.title}</h4>
                </div>
                <div className="bi-arrow" aria-hidden="true">→</div>
              </div>
            );
          })}
        </div>
        <p className="t-byline" style={{ marginTop: 24, color: teaser.color }}>
          Derleyen <span className="by-name">{writer.name}</span> <em>· Reaksiyoner Redaksiyonu</em>
        </p>
      </div>
    </section>
  );
}

// --- Teaser dispatcher ---
function Teaser({ teaser, onOpen }) {
  switch (teaser.type) {
    case "image":       return <ImageTeaser teaser={teaser} onOpen={onOpen} />;
    case "split":       return <SplitTeaser teaser={teaser} onOpen={onOpen} />;
    case "typo":        return <TypoTeaser teaser={teaser} onOpen={onOpen} />;
    case "tileRow":     return <TileRow teaser={teaser} onOpen={onOpen} />;
    case "briefing":    return <BriefingTeaser teaser={teaser} onOpen={onOpen} />;
    case "sectionHead": return <SectionHead title={teaser.title} note={teaser.note} />;
    default:            return null;
  }
}

// --- Footer ---
function Footer({ onNav }) {
  return (
    <footer className="footer">
      <div className="ft-inner">
        <div className="ft-brand">
          <a href="#" className="wordmark" onClick={(e) => { e.preventDefault(); onNav({ view: "home" }); }}>
            <span className="wmtxt">Reaksiyoner</span>
          </a>
          <p className="ft-tag">Bağımsız politik dergi. Yavaş okuma, derin bakış. İstanbul, 2019'dan bu yana.</p>
        </div>
        <div className="ft-cols">
          <div className="ft-col">
            <h5>Dergi</h5>
            <a href="#" onClick={(e) => { e.preventDefault(); onNav({ view: "home" }); }}>Magazin</a>
            <a href="#" onClick={(e) => { e.preventDefault(); onNav({ view: "feed" }); }}>Akış</a>
            <a href="#" onClick={(e) => { e.preventDefault(); onNav({ view: "dialog" }); }}>Diyalog</a>
            <a href="#">Arşiv</a>
            <a href="#">Künye</a>
          </div>
          <div className="ft-col">
            <h5>Formatlar</h5>
            {Object.entries(FORMATS).map(([id, f]) => (
              <a key={id} href="#">{f.label}</a>
            ))}
          </div>
          <div className="ft-col">
            <h5>İletişim</h5>
            <a href="#">redaksiyon@reaksiyoner.com.tr</a>
            <a href="#">İhbar hattı</a>
            <a href="#">Yazar olmak</a>
            <a href="#">Düzeltme talebi</a>
            <a href="#">Etik ilkeler</a>
          </div>
          <div className="ft-col">
            <h5>Takip et</h5>
            <a href="#">Bülten</a>
            <a href="#">RSS</a>
            <a href="#">Mastodon</a>
            <a href="#">Bluesky</a>
            <a href="#">Podcast</a>
          </div>
        </div>
      </div>
      <div className="ft-bot">
        <span>© 2026 Reaksiyoner Yayıncılık</span>
        <span className="dot">·</span>
        <span>Beyoğlu, İstanbul</span>
        <span className="dot">·</span>
        <a href="#">KVKK</a>
        <a href="#">Çerez tercihleri</a>
        <a href="#">Kullanım koşulları</a>
      </div>
    </footer>
  );
}

Object.assign(window, {
  initials, CoverPlaceholder, Header, IssueBand, SectionHead,
  Byline, FormatLabel, TypoTeaser, ImageTeaser, SplitTeaser, Tile, TileRow,
  BriefingTeaser, Teaser, Footer
});
