// Marsan Insights — single article reader.
// Renders a tiny markdown subset suited to long-form editorial:
//   ## H2  · ### H3  · paragraphs
//   - bullet lists
//   | header | … |  →  table
//   > blockquote
//   **bold**, *italic*

const MD = (raw) => {
  const out = [];
  const lines = (raw || '').split('\n');
  let i = 0;

  // Inline formatting: **bold**, *italic*, `code`.
  const inline = (text) => {
    const parts = [];
    let buf = '';
    let key = 0;
    const push = (el) => { if (buf) { parts.push(buf); buf = ''; } parts.push(<React.Fragment key={key++}>{el}</React.Fragment>); };
    let j = 0;
    while (j < text.length) {
      if (text.slice(j, j + 2) === '**') {
        const end = text.indexOf('**', j + 2);
        if (end > 0) {
          push(<strong style={{ color: '#0a1f17', fontWeight: 600 }}>{text.slice(j + 2, end)}</strong>);
          j = end + 2; continue;
        }
      }
      if (text[j] === '*') {
        const end = text.indexOf('*', j + 1);
        if (end > 0) { push(<em style={{ fontStyle: 'italic', color: '#a88841' }}>{text.slice(j + 1, end)}</em>); j = end + 1; continue; }
      }
      if (text[j] === '`') {
        const end = text.indexOf('`', j + 1);
        if (end > 0) { push(<code style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: '0.85em', background: 'rgba(201,165,92,0.10)', padding: '1px 6px', borderRadius: 2 }}>{text.slice(j + 1, end)}</code>); j = end + 1; continue; }
      }
      buf += text[j]; j++;
    }
    if (buf) parts.push(buf);
    return parts;
  };

  while (i < lines.length) {
    const ln = lines[i];

    if (/^### /.test(ln)) {
      out.push(<h3 key={i} style={{ fontFamily: 'Cormorant Garamond, serif', fontWeight: 500, fontSize: 22, color: '#0a1f17', margin: '32px 0 12px', letterSpacing: '-0.005em' }}>{inline(ln.slice(4))}</h3>);
      i++; continue;
    }
    if (/^## /.test(ln)) {
      out.push(<h2 key={i} style={{ fontFamily: 'Cormorant Garamond, serif', fontWeight: 400, fontSize: 32, color: '#0a1f17', margin: '52px 0 20px', letterSpacing: '-0.01em', lineHeight: 1.2 }}>{inline(ln.slice(3))}</h2>);
      i++; continue;
    }
    if (/^> /.test(ln)) {
      const buf = [];
      while (i < lines.length && /^> /.test(lines[i])) { buf.push(lines[i].slice(2)); i++; }
      out.push(
        <blockquote key={i} style={{
          fontFamily: 'Cormorant Garamond, serif', fontSize: 24, fontStyle: 'italic',
          color: '#0a1f17', borderLeft: '3px solid #c9a55c',
          padding: '8px 0 8px 24px', margin: '32px 0', lineHeight: 1.5,
        }}>{inline(buf.join(' '))}</blockquote>
      );
      continue;
    }
    if (/^\|/.test(ln)) {
      // Accept any line that starts with `|` so separator rows like `|---|---|` are
      // consumed by the table block instead of falling through to the paragraph
      // fallback (which used to deadlock the loop).
      const rows = [];
      while (i < lines.length && /^\|/.test(lines[i])) { rows.push(lines[i]); i++; }
      const cells = rows.map(r => r.split('|').slice(1, -1).map(c => c.trim()));
      const header = cells[0];
      const body = cells.slice(1).filter(r => !r.every(c => /^[-:\s]*$/.test(c)));
      out.push(
        <div key={'t' + i} style={{ overflowX: 'auto', margin: '24px 0' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
            <thead>
              <tr style={{ background: '#efe8d8' }}>
                {header.map((h, k) => <th key={k} style={{ padding: '12px 16px', textAlign: 'left', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#8c857b', borderBottom: '1px solid #d9cfb8' }}>{inline(h)}</th>)}
              </tr>
            </thead>
            <tbody>
              {body.map((row, r) => (
                <tr key={r} style={{ borderBottom: '1px solid #efe8d8' }}>
                  {row.map((c, k) => <td key={k} style={{ padding: '12px 16px', color: '#0a1f17' }}>{inline(c)}</td>)}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
      continue;
    }
    if (/^- /.test(ln)) {
      const items = [];
      while (i < lines.length && /^- /.test(lines[i])) { items.push(lines[i].slice(2)); i++; }
      out.push(
        <ul key={'u' + i} style={{ margin: '16px 0 16px 0', paddingLeft: 20, lineHeight: 1.85, color: '#4a4540', fontSize: 16 }}>
          {items.map((it, k) => <li key={k} style={{ marginBottom: 6 }}>{inline(it)}</li>)}
        </ul>
      );
      continue;
    }
    if (/^\d+\. /.test(ln)) {
      const items = [];
      while (i < lines.length && /^\d+\. /.test(lines[i])) { items.push(lines[i].replace(/^\d+\. /, '')); i++; }
      out.push(
        <ol key={'o' + i} style={{ margin: '16px 0 16px 0', paddingLeft: 24, lineHeight: 1.85, color: '#4a4540', fontSize: 16 }}>
          {items.map((it, k) => <li key={k} style={{ marginBottom: 6 }}>{inline(it)}</li>)}
        </ol>
      );
      continue;
    }
    if (ln.trim() === '') { i++; continue; }
    // Paragraph: collect contiguous non-blank lines.
    const startI = i;
    const buf = [];
    while (i < lines.length && lines[i].trim() && !/^(##|###|>|-|\d+\.|\|)/.test(lines[i])) { buf.push(lines[i]); i++; }
    if (buf.length) {
      out.push(<p key={'p' + i} style={{ fontSize: 16, lineHeight: 1.85, color: '#4a4540', margin: '0 0 18px' }}>{inline(buf.join(' '))}</p>);
    }
    // Hard guard: if no branch advanced `i`, force a step. Prevents any future
    // malformed line from deadlocking the renderer and crashing the tab.
    if (i === startI) i++;
  }
  return out;
};

const ArticlePage = () => {
  if (window.MarsanMobile && window.MarsanMobile.isMobile && window.MarsanMobile.isMobile()) {
    return <window.MarsanMobile.Article />;
  }
  const C = window.MarsanComponents;
  const { Icon } = C;
  const slug = new URLSearchParams(window.location.search).get('slug');
  const [article, setArticle] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [related, setRelated] = React.useState([]);

  React.useEffect(() => {
    if (!slug) { setError('No article specified'); return; }
    window.MarsanAPI.articles.get(slug)
      .then(r => {
        setArticle(r.item);
        document.title = r.item.title + ' — Marsan Insights';
      })
      .catch(() => setError('Article not found'));
    window.MarsanAPI.articles.list().then(r => setRelated((r.items || []).filter(a => a.slug !== slug).slice(0, 3)));
  }, [slug]);

  if (error) {
    return (
      <div className="ms-root" style={{ minHeight: '100vh', background: '#f6f1e6' }}>
        <C.Header active="Insights" light={false} />
        <section style={{ padding: '120px 56px', textAlign: 'center' }}>
          <h1 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 56, color: '#0a1f17' }}>{error}</h1>
          <a href="/insights.html" className="ms-btn ms-btn-primary" style={{ marginTop: 24 }}>Browse all insights</a>
        </section>
        <C.Footer />
      </div>
    );
  }

  if (!article) {
    return (
      <div className="ms-root" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div className="ms-loader" />
      </div>
    );
  }

  return (
    <div className="ms-root" style={{ minHeight: '100vh', background: '#f6f1e6' }}>
      <C.Header active="Insights" light={false} />

      {/* Cover */}
      <section style={{ position: 'relative', height: 520, overflow: 'hidden', background: '#0a1f17' }}>
        {article.cover_url
          ? <img src={article.cover_url} alt={article.title}
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
          : <div className="ms-img-ph" style={{ position: 'absolute', inset: 0 }} />}
        <div style={{ position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(10,31,23,0.4) 0%, transparent 30%, rgba(10,31,23,0.85) 100%)' }} />
        <div style={{ position: 'absolute', bottom: 56, left: 56, right: 56, maxWidth: 900 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(232,220,193,0.7)', marginBottom: 16 }}>
            <a href="/insights.html" style={{ color: 'inherit', textDecoration: 'none' }}>Insights</a>
            <Icon name="chevron" size={12} />
            <span style={{ color: '#e2bd6b' }}>{article.category}</span>
          </div>
          <h1 className="ms-h1" style={{ fontFamily: 'Cormorant Garamond, serif', fontWeight: 300, fontSize: 56, color: '#f6f1e6', margin: '0 0 16px', lineHeight: 1.1 }}>
            {article.title}
          </h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 13, color: 'rgba(232,220,193,0.8)', flexWrap: 'wrap' }}>
            <span>By Sandeep Reddy Sanappa</span>
            <span style={{ color: 'rgba(232,220,193,0.4)' }}>·</span>
            <span>{article.read_min} min read</span>
            <span style={{ color: 'rgba(232,220,193,0.4)' }}>·</span>
            <span>{new Date(article.published_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' })}</span>
          </div>
        </div>
      </section>

      {/* Body */}
      <section style={{ padding: '80px 56px', maxWidth: 800, margin: '0 auto' }}>
        {article.excerpt && (
          <p style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 24, fontStyle: 'italic', color: '#0a1f17', lineHeight: 1.5, margin: '0 0 48px', paddingBottom: 32, borderBottom: '1px solid #d9cfb8' }}>
            {article.excerpt}
          </p>
        )}
        <div className="ms-article-body">
          {MD(article.body)}
        </div>
      </section>

      {/* Author / footer */}
      <section style={{ padding: '64px 56px', background: '#efe8d8' }}>
        <div style={{ maxWidth: 800, margin: '0 auto', display: 'grid', gridTemplateColumns: '120px 1fr', gap: 24, alignItems: 'flex-start' }} className="ms-collapse-mobile">
          <img src="/assets/founder-sandeep.png" alt="Sandeep Reddy Sanappa"
            style={{ width: 120, height: 120, objectFit: 'cover', objectPosition: 'center top', filter: 'grayscale(0.2)' }} />
          <div>
            <div className="ms-eyebrow" style={{ marginBottom: 8 }}>About the author</div>
            <h3 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 26, color: '#0a1f17', margin: '0 0 8px' }}>Sandeep Reddy Sanappa</h3>
            <p style={{ fontSize: 14, lineHeight: 1.7, color: '#4a4540', margin: '0 0 16px' }}>
              Founder &amp; Managing Director, Marsan Properties. Sandeep has been advising private and NRI buyers on Hyderabad land for over a decade. He writes the Marsan Insights series quarterly.
            </p>
            <a href="/enquire.html?type=callback" className="ms-btn ms-btn-ghost-dark ms-btn-sm">Schedule a 20-min consultation <Icon name="arrow" size={12} /></a>
          </div>
        </div>
      </section>

      {/* Related */}
      {related.length > 0 && (
        <section style={{ padding: '80px 56px' }}>
          <div style={{ maxWidth: 1200, margin: '0 auto' }}>
            <div className="ms-eyebrow" style={{ marginBottom: 12 }}>Continue reading</div>
            <h2 className="ms-h2" style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 36, color: '#0a1f17', margin: '0 0 32px' }}>Other notes from the desk.</h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }} className="ms-collapse-mobile">
              {related.map(r => (
                <a key={r.slug} href={'/article.html?slug=' + r.slug} style={{ textDecoration: 'none', color: 'inherit' }}>
                  <div style={{ aspectRatio: '4/3', marginBottom: 16, position: 'relative', overflow: 'hidden', background: '#0a1f17' }}>
                    {r.cover_url
                      ? <img src={r.cover_url} alt={r.title} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                      : <div className="ms-img-ph" style={{ position: 'absolute', inset: 0 }} />}
                  </div>
                  <div className="ms-meta" style={{ color: '#a88841', marginBottom: 8 }}>{r.category.toUpperCase()}</div>
                  <h3 style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 22, color: '#0a1f17', margin: '0 0 12px', lineHeight: 1.2 }}>{r.title}</h3>
                  <div style={{ fontSize: 12, color: '#8c857b' }}>{r.read_min} min read</div>
                </a>
              ))}
            </div>
          </div>
        </section>
      )}

      <C.Footer />
    </div>
  );
};

window.ArticlePage = ArticlePage;
