// =============================================================================
// Article.jsx — shared renderer for long-form pages.
//
// Used by every /articles/*.html (Sun School) and by /privacy + /terms.
// Each page supplies a plain data object; this file owns all the layout, so the
// seven articles stay visually identical and there is one place to restyle.
//
// Block schema consumed by <ArticleBody blocks={…}>:
//   { t: 'p',       html }                     paragraph (inline html allowed)
//   { t: 'lede',    html }                     opening paragraph, larger
//   { t: 'h2',      text, id }                 section heading
//   { t: 'h3',      text }                     sub-heading
//   { t: 'ul'|'ol', items: [html] }            list
//   { t: 'callout', title, html }              bordered aside
//   { t: 'stats',   items: [{ n, label }] }    up-to-3 big numbers
//   { t: 'table',   head: [], rows: [[]] }     data table
//   { t: 'img',     src, alt, caption }        figure
// =============================================================================

// Body copy carries inline <strong>/<a>, so blocks render through
// dangerouslySetInnerHTML. Every block is author-written and static — no user
// input ever reaches this renderer.
const raw = (html) => ({ __html: html });

const ArticleBody = ({ blocks }) => (
  <div className="hws-prose">
    {blocks.map((b, i) => {
      switch (b.t) {
        case 'lede':
          return <p key={i} className="hws-lede" dangerouslySetInnerHTML={raw(b.html)} />;
        case 'p':
          return <p key={i} dangerouslySetInnerHTML={raw(b.html)} />;
        case 'h2':
          return <h2 key={i} id={b.id}>{b.text}</h2>;
        case 'h3':
          return <h3 key={i}>{b.text}</h3>;
        case 'ul':
          return <ul key={i}>{b.items.map((it, j) => <li key={j} dangerouslySetInnerHTML={raw(it)} />)}</ul>;
        case 'ol':
          return <ol key={i}>{b.items.map((it, j) => <li key={j} dangerouslySetInnerHTML={raw(it)} />)}</ol>;
        case 'callout':
          return (
            <aside key={i} className="hws-callout">
              {b.title && <div className="hws-callout-h">{b.title}</div>}
              <div dangerouslySetInnerHTML={raw(b.html)} />
            </aside>
          );
        case 'stats':
          return (
            <div key={i} className="hws-stats">
              {b.items.map((s, j) => (
                <div key={j} className="hws-stat"><b>{s.n}</b><span>{s.label}</span></div>
              ))}
            </div>
          );
        case 'table':
          return (
            <div key={i} className="hws-tablewrap">
              <table className="hws-table">
                <thead><tr>{b.head.map((h, j) => <th key={j}>{h}</th>)}</tr></thead>
                <tbody>
                  {b.rows.map((r, j) => (
                    <tr key={j}>{r.map((c, k) => <td key={k} dangerouslySetInnerHTML={raw(c)} />)}</tr>
                  ))}
                </tbody>
              </table>
            </div>
          );
        case 'img':
          return (
            <figure key={i} style={{ margin: 0 }}>
              <img src={b.src} alt={b.alt || ''} style={{ width: '100%', borderRadius: 18, border: '2px solid rgba(61,47,35,0.10)' }} />
              {b.caption && (
                <figcaption style={{ fontSize: 13, opacity: 0.7, marginTop: 10, fontStyle: 'italic' }}>{b.caption}</figcaption>
              )}
            </figure>
          );
        default:
          return null;
      }
    })}
  </div>
);

// ── Hero ─────────────────────────────────────────────────────────────────────
const ArticleHero = ({ meta }) => (
  <header style={{ maxWidth: 860, margin: '0 auto', padding: '36px 24px 0' }}>
    <a href="/sun-school" style={{
      display: 'inline-flex', alignItems: 'center', gap: 8, textDecoration: 'none',
      fontFamily: 'var(--font-display)', fontSize: 14, letterSpacing: '0.08em',
      textTransform: 'uppercase', color: 'var(--brown-soft)', marginBottom: 26,
    }}>← Back to Sun School</a>

    <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center', marginBottom: 16 }}>
      <span style={{
        background: meta.tagBg || 'var(--brown)', color: meta.tagColor || 'var(--sun)',
        fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.09em',
        textTransform: 'uppercase', padding: '6px 13px', borderRadius: 999,
      }}>{meta.tag}</span>
      <span style={{ fontSize: 13, color: 'var(--brown-soft)', fontWeight: 700, letterSpacing: '0.04em' }}>{meta.category}</span>
    </div>

    <h1 style={{
      fontFamily: 'var(--font-display)', fontSize: 'clamp(34px, 6.5vw, 58px)',
      lineHeight: 1.04, letterSpacing: '0.005em', color: 'var(--brown)',
      margin: '0 0 18px', textTransform: 'uppercase', fontWeight: 400,
    }}>{meta.title}</h1>

    {meta.script && (
      <div style={{
        fontFamily: 'var(--font-script)', color: 'var(--orange)', fontSize: 27,
        transform: 'rotate(-2deg)', transformOrigin: 'left center', marginBottom: 20,
      }}>{meta.script}</div>
    )}

    <div style={{
      display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center',
      fontSize: 13.5, color: 'var(--brown-soft)', fontWeight: 600,
      paddingBottom: 26, borderBottom: '2px solid rgba(61,47,35,0.12)',
    }}>
      <span>{meta.author}</span><span aria-hidden="true">·</span>
      <span>{meta.date}</span><span aria-hidden="true">·</span>
      <span>{meta.read} read</span>
    </div>
  </header>
);

// ── Medical disclaimer ───────────────────────────────────────────────────────
// Sun care sits next to health advice. Every article carries this so we never
// read as a substitute for a dermatologist.
const ArticleDisclaimer = () => (
  <div style={{ maxWidth: 860, margin: '48px auto 0', padding: '0 24px' }}>
    <div style={{
      background: 'rgba(61,47,35,0.05)', border: '1.5px dashed rgba(61,47,35,0.22)',
      borderRadius: 14, padding: '18px 20px', fontSize: 13.5, lineHeight: 1.6,
      color: 'var(--brown-soft)', fontFamily: 'var(--font-body)',
    }}>
      <strong style={{ color: 'var(--brown)' }}>General information, not medical advice.</strong>{' '}
      Hawaiian Style has made sun care since 1995, but we are not dermatologists. This
      article summarises published guidance from the sources listed below. If you have a
      skin condition, a burn that blisters, a mole that is changing, or you are treating a
      young child, please talk to a doctor.{' '}
      <span style={{ fontFamily: 'var(--font-thai)' }}>
        บทความนี้ให้ข้อมูลทั่วไป ไม่ใช่คำแนะนำทางการแพทย์ หากมีอาการผิดปกติ กรุณาปรึกษาแพทย์
      </span>
    </div>
  </div>
);

// ── Sources ──────────────────────────────────────────────────────────────────
const ArticleSources = ({ sources }) => (
  <section style={{ maxWidth: 860, margin: '44px auto 0', padding: '0 24px' }}>
    <h2 style={{
      fontFamily: 'var(--font-display)', fontSize: 22, textTransform: 'uppercase',
      letterSpacing: '0.06em', color: 'var(--brown)', fontWeight: 400,
      margin: '0 0 16px', paddingTop: 30, borderTop: '2px solid rgba(61,47,35,0.12)',
    }}>Sources</h2>
    <div className="hws-sources">
      <ol>
        {sources.map((s, i) => (
          <li key={i}>
            <a href={s.url} target="_blank" rel="noopener noreferrer nofollow">{s.title}</a>
            {s.pub && <span style={{ color: 'var(--brown-soft)' }}> — {s.pub}</span>}
          </li>
        ))}
      </ol>
    </div>
  </section>
);

// ── Next-up navigation ───────────────────────────────────────────────────────
const ArticleNext = ({ items }) => (
  <section style={{ maxWidth: 860, margin: '56px auto 0', padding: '0 24px' }}>
    <Eyebrow>★ Keep reading</Eyebrow>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 16, marginTop: 16 }}>
      {items.map((a) => (
        <a key={a.href} href={a.href} style={{
          background: 'var(--paper-soft)', border: '1.5px solid rgba(61,47,35,0.12)',
          borderRadius: 16, padding: '20px 22px', textDecoration: 'none',
          color: 'var(--brown)', display: 'block', boxShadow: 'var(--shadow-sm)',
        }}>
          <div style={{
            fontFamily: 'var(--font-display)', fontSize: 12, letterSpacing: '0.09em',
            textTransform: 'uppercase', color: 'var(--orange)', marginBottom: 8,
          }}>{a.tag}</div>
          <div style={{ fontWeight: 800, fontSize: 16, lineHeight: 1.35 }}>{a.title}</div>
          <div style={{ fontSize: 13, color: 'var(--brown-soft)', marginTop: 8 }}>{a.read} read →</div>
        </a>
      ))}
    </div>
  </section>
);

// ── Whole-page composition ───────────────────────────────────────────────────
const ArticlePage = ({ meta, blocks, sources, next = [] }) => (
  <>
    <TopBar />
    <Nav cartCount={0} />
    <ArticleHero meta={meta} />
    {meta.img && (
      <div style={{ maxWidth: 860, margin: '28px auto 0', padding: '0 24px' }}>
        <img src={meta.img} alt="" style={{
          width: '100%', borderRadius: 22, border: '2px solid rgba(61,47,35,0.10)',
          boxShadow: 'var(--shadow-md)', aspectRatio: '16 / 9', objectFit: 'cover',
        }} />
      </div>
    )}
    <main style={{ maxWidth: 860, margin: '0 auto', padding: '34px 24px 0' }}>
      <ArticleBody blocks={blocks} />
    </main>
    <ArticleDisclaimer />
    {sources && sources.length > 0 && <ArticleSources sources={sources} />}
    {next.length > 0 && <ArticleNext items={next} />}
    <div style={{ height: 40 }} />
    <Footer />
  </>
);

// ── Legal pages (Privacy / Terms) ────────────────────────────────────────────
// Same prose styling, minus the article furniture — no hero image, no sources,
// no "keep reading".
const LegalPage = ({ title, thaiTitle, updated, intro, blocks, toc }) => (
  <>
    <TopBar />
    <Nav cartCount={0} />
    <header style={{ maxWidth: 860, margin: '0 auto', padding: '40px 24px 0' }}>
      <Eyebrow>★ Sahatavesin Import Export Co., Ltd.</Eyebrow>
      <h1 style={{
        fontFamily: 'var(--font-display)', fontSize: 'clamp(34px, 6.5vw, 56px)',
        lineHeight: 1.05, color: 'var(--brown)', margin: '14px 0 6px',
        textTransform: 'uppercase', fontWeight: 400,
      }}>{title}</h1>
      {thaiTitle && (
        <div style={{ fontFamily: 'var(--font-thai)', fontSize: 19, color: 'var(--brown-soft)', fontWeight: 600 }}>{thaiTitle}</div>
      )}
      <div style={{
        marginTop: 18, paddingBottom: 24, borderBottom: '2px solid rgba(61,47,35,0.12)',
        fontSize: 13.5, color: 'var(--brown-soft)', fontWeight: 600,
      }}>Last updated: {updated}</div>
    </header>

    <main style={{ maxWidth: 860, margin: '0 auto', padding: '30px 24px 0' }}>
      <div className="hws-prose">
        <p className="hws-lede" dangerouslySetInnerHTML={raw(intro)} />
      </div>

      {toc && (
        <nav aria-label="On this page" style={{
          marginTop: 30, background: 'var(--paper-soft)', borderRadius: 16,
          border: '1.5px solid rgba(61,47,35,0.12)', padding: '20px 24px',
        }}>
          <div style={{
            fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.09em',
            textTransform: 'uppercase', color: 'var(--orange)', marginBottom: 12,
          }}>On this page</div>
          {/* These pages set <base href="/">, so a bare "#id" resolves against the
              base and sent the reader to the home page. Anchor each fragment to the
              current path instead. */}
          <ol style={{ margin: 0, paddingLeft: 20, display: 'flex', flexDirection: 'column', gap: 8, fontSize: 15 }}>
            {toc.map((t) => (
              <li key={t.id}>
                <a href={location.pathname + '#' + t.id} style={{ color: 'var(--brown)' }}>{t.label}</a>
              </li>
            ))}
          </ol>
        </nav>
      )}

      <div style={{ marginTop: 10 }}>
        <ArticleBody blocks={blocks} />
      </div>
    </main>
    <div style={{ height: 60 }} />
    <Footer />
  </>
);
