// Shared article-page layout — used by every articles/<slug>.html
// Each article file defines an ARTICLE object and renders <ArticleLayout article={ARTICLE} />.
// Bilingual: all visible text fields are { he, en }; body/faq are { he:[...], en:[...] }.

const ARTICLE_TAGS = {
  blue:   { bg: 'var(--blue-50)',   fg: 'var(--blue-600)' },
  orange: { bg: 'var(--orange-50)', fg: 'var(--orange)' },
  purple: { bg: 'var(--purple-50)', fg: 'var(--purple-600)' },
  green:  { bg: 'var(--green-50)',  fg: 'var(--green)' },
};

// Pick the right language out of a { he, en } field (or return as-is for plain strings).
function pickLang(field, lang) {
  if (field && typeof field === 'object' && ('he' in field || 'en' in field)) {
    return lang === 'en' ? field.en : field.he;
  }
  return field;
}

// Render an array of content blocks. `text` may contain inline HTML (<strong>, <a>…).
function ArticleBlocks({ blocks }) {
  return (
    <React.Fragment>
      {(blocks || []).map((b, i) => {
        if (b.type === 'h2') return <h2 key={i}>{b.text}</h2>;
        if (b.type === 'h3') return <h3 key={i}>{b.text}</h3>;
        if (b.type === 'ul')
          return <ul key={i}>{b.items.map((it, j) => <li key={j} dangerouslySetInnerHTML={{ __html: it }} />)}</ul>;
        if (b.type === 'ol')
          return <ol key={i}>{b.items.map((it, j) => <li key={j} dangerouslySetInnerHTML={{ __html: it }} />)}</ol>;
        if (b.type === 'quote')
          return (
            <blockquote key={i}>
              {b.text}
              {b.cite && <cite>{b.cite}</cite>}
            </blockquote>
          );
        return <p key={i} dangerouslySetInnerHTML={{ __html: b.text }} />;
      })}
    </React.Fragment>
  );
}

function buildArticleSchema(a) {
  const schema = {
    '@context': 'https://schema.org',
    '@type': 'Article',
    headline: a.title.he,
    description: a.excerpt.he,
    inLanguage: 'he-IL',
    author: { '@type': 'Person', name: 'Tal Galik Lavi' },
    publisher: { '@type': 'Organization', name: 'Lawyerit', url: 'https://lawyer-it.com' },
  };
  if (a.datePublished) schema.datePublished = a.datePublished;
  if (a.dateModified) schema.dateModified = a.dateModified;
  if (a.url) schema.mainEntityOfPage = { '@type': 'WebPage', '@id': a.url };
  return schema;
}

function buildFaqSchema(faqList) {
  return {
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: faqList.map(f => ({
      '@type': 'Question',
      name: f.q,
      acceptedAnswer: { '@type': 'Answer', text: f.a },
    })),
  };
}

function ArticleLayout({ article }) {
  const lang = useLang();
  const L = (field) => pickLang(field, lang);
  const tag = ARTICLE_TAGS[article.tagColor] || ARTICLE_TAGS.blue;
  const body = article.body ? article.body[lang] || article.body.he : [];
  const faq = article.faq ? article.faq[lang] || article.faq.he : null;

  return (
    <article>
      {/* Breadcrumb */}
      <div className="container" style={{ paddingTop: 20, paddingBottom: 12, fontSize: 13, color: 'var(--muted)' }}>
        <a href="Lawyerit Homepage.html" style={{ color: 'var(--muted)' }}>{t(lang, 'דף הבית', 'Home')}</a>
        <span style={{ margin: '0 8px', color: 'var(--border)' }}>/</span>
        <a href="insights.html" style={{ color: 'var(--muted)' }}>{t(lang, 'מאמרים', 'Articles')}</a>
        <span style={{ margin: '0 8px', color: 'var(--border)' }}>/</span>
        <span style={{ color: 'var(--ink-2)' }}>{L(article.title)}</span>
      </div>

      {/* Hero */}
      <header className="container article-hero">
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
          <span className="en" style={{
            fontSize: 11, fontWeight: 700, letterSpacing: '0.06em',
            color: tag.fg, background: tag.bg, padding: '4px 10px', borderRadius: 5,
          }}>{L(article.tag)}</span>
          <span style={{ fontSize: 13, color: 'var(--muted-2)' }}>{L(article.date)}</span>
          <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--muted-2)' }} />
          <span style={{ fontSize: 13, color: 'var(--muted-2)' }}>{L(article.readTime)}</span>
        </div>

        <h1 style={{ fontSize: 'clamp(30px, 4vw, 46px)', lineHeight: 1.12, letterSpacing: '-0.03em', marginBottom: 18 }}>
          {L(article.title)}
        </h1>
        <p style={{ fontSize: 19, lineHeight: 1.6, color: 'var(--muted)' }}>{L(article.excerpt)}</p>

        {/* Author */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 24, paddingTop: 20, borderTop: '1px solid var(--border-2)' }}>
          <div className="en" style={{
            width: 36, height: 36, borderRadius: '50%',
            background: 'var(--turquoise-50)', color: 'var(--turquoise-700)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 700, fontSize: 13,
          }}>TG</div>
          <div>
            <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 14 }}>
              {t(lang, 'עו״ד טל גלק לביא', 'Tal Galik Lavi, Adv.')}
            </div>
            <div style={{ fontSize: 12, color: 'var(--muted-2)' }}>
              {t(lang, 'Lawyerit — משפט, פרטיות ורגולציה', 'Lawyerit — Law, Privacy & Regulation')}
            </div>
          </div>
        </div>
      </header>

      {/* Body */}
      <div className="container article-body">
        <ArticleBlocks blocks={body} />

        {faq && faq.length > 0 && (
          <React.Fragment>
            <h2>{t(lang, 'שאלות נפוצות', 'Frequently asked questions')}</h2>
            {faq.map((f, i) => (
              <div key={i} style={{ marginBottom: 20 }}>
                <h3 style={{ marginBottom: 6 }}>{f.q}</h3>
                <p>{f.a}</p>
              </div>
            ))}
          </React.Fragment>
        )}

        <p className="article-disclaimer">
          {t(lang,
            'האמור לעיל הוא מידע כללי בלבד ואינו מהווה ייעוץ משפטי או תחליף לו. לקבלת ייעוץ המותאם לנסיבות הספציפיות שלכם — דברו איתנו.',
            'The above is general information only and does not constitute legal advice. For guidance tailored to your specific circumstances — talk to us.'
          )}
        </p>

        {article.sources && article.sources.length > 0 && (
          <details className="article-sources">
            <summary>{t(lang, 'מקורות', 'Sources')}</summary>
            <ul>
              {article.sources.map((s, i) => (
                <li key={i}>
                  <a href={s.url} target="_blank" rel="noopener noreferrer">{s.title}</a>
                </li>
              ))}
            </ul>
          </details>
        )}

        <div style={{ marginTop: 48, paddingTop: 24, borderTop: '1px solid var(--border-2)' }}>
          <a href="insights.html" style={{
            fontSize: 14, fontWeight: 500, color: 'var(--turquoise-700)',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M10 4L6 8l4 4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            {t(lang, 'חזרה לכל המאמרים', 'Back to all articles')}
          </a>
        </div>
      </div>

      {/* Closing CTA (shared with the rest of the site) */}
      <div style={{ marginTop: 80 }}>
        <FinalCTA />
      </div>

      {/* Structured data for SEO + AI search (GEO) */}
      <script type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(buildArticleSchema(article)) }} />
      {article.faq && article.faq.he && article.faq.he.length > 0 && (
        <script type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(buildFaqSchema(article.faq.he)) }} />
      )}

      <style>{`
        .article-hero { max-width: 760px; margin-top: 24px; margin-bottom: 40px; }
        .article-body { max-width: 760px; font-size: 18px; line-height: 1.85; color: var(--ink-2); }
        .article-body h2 { font-size: 26px; line-height: 1.25; margin: 44px 0 14px; letter-spacing: -0.02em; }
        .article-body h3 { font-size: 20px; line-height: 1.3; margin: 30px 0 10px; }
        .article-body p { margin: 0 0 20px; }
        .article-body ul, .article-body ol { margin: 0 0 22px; padding-inline-start: 24px; }
        .article-body li { margin-bottom: 10px; }
        .article-body a { color: var(--turquoise-700); text-decoration: underline; text-underline-offset: 2px; }
        .article-body strong { color: var(--ink); font-weight: 700; }
        .article-body blockquote {
          margin: 28px 0; padding: 6px 20px;
          border-inline-start: 3px solid var(--turquoise);
          font-size: 20px; line-height: 1.6; color: var(--ink);
        }
        .article-body blockquote cite { display: block; margin-top: 10px; font-size: 14px; color: var(--muted-2); font-style: normal; }
        .article-disclaimer {
          font-size: 14px; line-height: 1.6; color: var(--muted-2);
          background: var(--bg-2); border: 1px solid var(--border-2);
          border-radius: 10px; padding: 14px 16px; margin-top: 36px;
        }
        .article-sources { margin-top: 20px; font-size: 14px; color: var(--muted); }
        .article-sources summary { cursor: pointer; font-weight: 500; }
        .article-sources ul { margin: 12px 0 0; padding-inline-start: 22px; }
        .article-sources a { color: var(--turquoise-700); }
        @media (max-width: 900px) { .article-body { font-size: 17px; } }
      `}</style>
    </article>
  );
}

Object.assign(window, { ArticleLayout, ARTICLE_TAGS });
