﻿/* global React */

// ── Inject animation keyframes once ───────────────────────────────────────────
const _nrCss = document.createElement('style');
_nrCss.textContent = `
  @keyframes nr-unfold {
    0%   { transform: scaleX(0.42) scaleY(0.42); opacity: 0; }
    38%  { transform: scaleX(0.42) scaleY(1);    opacity: 0.75; }
    100% { transform: scaleX(1)    scaleY(1);    opacity: 1; }
  }
  @keyframes nr-fold {
    0%   { transform: scaleX(1)    scaleY(1);    opacity: 1; }
    55%  { transform: scaleX(0.42) scaleY(1);    opacity: 0.6; }
    100% { transform: scaleX(0.42) scaleY(0.42); opacity: 0; }
  }
  @keyframes nr-out-left {
    from { transform: perspective(1200px) rotateY(0deg);   opacity: 1; }
    to   { transform: perspective(1200px) rotateY(-82deg); opacity: 0; }
  }
  @keyframes nr-in-right {
    from { transform: perspective(1200px) rotateY(82deg);  opacity: 0; }
    to   { transform: perspective(1200px) rotateY(0deg);   opacity: 1; }
  }
  @keyframes nr-out-right {
    from { transform: perspective(1200px) rotateY(0deg);   opacity: 1; }
    to   { transform: perspective(1200px) rotateY(82deg);  opacity: 0; }
  }
  @keyframes nr-in-left {
    from { transform: perspective(1200px) rotateY(-82deg); opacity: 0; }
    to   { transform: perspective(1200px) rotateY(0deg);   opacity: 1; }
  }
  .nr-nav-btn:hover { border-color: rgba(244,239,224,0.8) !important; color: var(--cream) !important; }
  .nr-src-pill { transition: opacity 150ms; }
  .nr-src-pill:hover { opacity: 0.85; }
`;
document.head.appendChild(_nrCss);

// ── Data ──────────────────────────────────────────────────────────────────────
const NEWS = [
  {
    src: "The Hindu", date: "9 May 2025", min: 4,
    title: "Old guard, new blood, and a Pravah Solution boost contributed to TMC's success",
    dek: "If the Chief Minister got the veterans, the newcomers were endorsed by the party along with Pravah Solution, who helped assure a decisive victory…",
    body: "Pravah Solution's deployment of micro-targeted voter outreach across 47 booths in the contested segments is widely credited with shoring up margins in seats that had been considered toss-ups just weeks before polling day. The firm's proprietary booth-level data model flagged 11 swing constituencies early, allowing the party to reallocate canvassing resources with precision.",
  },
  {
    src: "Outlook", date: "2 May 2025", min: 6,
    title: "Does ideology matter at all in today's Indian politics?",
    dek: "A panel of strategists, including Pravah Solution's leadership team, debate the death of ideology and the rise of the winnability factor.",
    body: "In a wide-ranging roundtable, Pravah Solution's founding partner argued that ideology is not dead — it has simply been subordinated to performance metrics in the minds of voters. 'People want roads, water, and jobs first. If a candidate delivers on those, ideology becomes a distant second,' he told moderators, drawing sharp agreement from two of the five panellists.",
  },
  {
    src: "Indian Express", date: "18 Apr 2025", min: 5,
    title: "The bottom line of the election is trust: Pravah Solution's founders",
    dek: "In a discussion on the role of consultants in modern elections, industry leaders shared insights into their experiences with prominent figures.",
    body: "Pravah Solution traces its emphasis on trust-building to a 2021 campaign that nearly went sideways when polling data and ground intelligence diverged by double digits. 'We shut down our models and spent three days just listening in villages. That recalibration saved the campaign,' one founder recalled. The firm now mandates ground-truth sessions every ten days regardless of what the numbers say.",
  },
  {
    src: "Mid-Day", date: "5 Jun 2024", min: 7,
    title: "Lok Sabha 2024: In West Bengal, Mamata Banerjee magic holds!",
    dek: "The success of Mamata's manoeuvres in checking the BJP's rise this general election suggests that India's only chief minister was always confident…",
    body: "Analysts point to a ground mobilisation strategy that Pravah Solution helped design for allied campaigns — a constituency-by-constituency activation plan that prioritised women voters aged 25–45, a demographic whose turnout jumped six points compared to 2019. The outcome reinforced the firm's thesis that last-mile voter contact, not advertising, decides close contests.",
  },
  {
    src: "LiveMint", date: "12 Mar 2024", min: 5,
    title: "Grassroots focus, cinematic posters: How Pravah Solution powers Andhra",
    dek: "Pravah Solution's core strength lies in its ability to work at the grassroots, analyse public pulse, and grasp intricate political nuances.",
    body: "The Andhra Pradesh campaign saw Pravah Solution deploy a team of 120 field researchers across 23 districts over six weeks, conducting 18,000 door-to-door interviews. The resulting sentiment map was refreshed weekly and fed directly into the creative team's briefings — an integration of research and production that the firm's creative director described as 'the closest thing we have to a real-time campaign nervous system.'",
  },
  {
    src: "India Today", date: "28 Jan 2024", min: 4,
    title: "How important is an election strategist for a political party?",
    dek: "Industry leaders share insights into their experiences with prominent political figures across India's diverse electoral geographies.",
    body: "When India Today asked Pravah Solution to quantify the value of strategic consultancy, the answer was characteristically data-forward: across the 14 campaigns the firm had advised in the previous 18 months, candidates who followed the recommended messaging framework outperformed their own internal projections by an average of 4.2 percentage points — a margin that proved decisive in nine of those races.",
  },
];

const SRC_COLORS = {
  "The Hindu":      "#1a3a5c",
  "Outlook":        "var(--ink)",
  "Indian Express": "var(--teal)",
  "Mid-Day":        "#c8860a",
  "LiveMint":       "#1a3a5c",
  "India Today":    "#b42c2c",
};

// ── NewsReader modal ──────────────────────────────────────────────────────────
const ANIM_DUR = 260;

const NewsReader = ({ startIndex, onClose }) => {
  const [current, setCurrent]   = React.useState(startIndex);
  const [anim, setAnim]         = React.useState('nr-unfold 580ms cubic-bezier(.4,0,.2,1) forwards');
  const busyRef                 = React.useRef(false);
  const touchStartX             = React.useRef(null);

  // Reset when startIndex changes (new card clicked)
  React.useEffect(() => {
    setCurrent(startIndex);
    setAnim('nr-unfold 580ms cubic-bezier(.4,0,.2,1) forwards');
    busyRef.current = false;
  }, [startIndex]);

  // Body scroll lock
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  // Keyboard navigation
  React.useEffect(() => {
    const h = (e) => {
      if (e.key === 'ArrowRight') go('next');
      if (e.key === 'ArrowLeft')  go('prev');
      if (e.key === 'Escape')     handleClose();
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  });

  const go = (dir) => {
    if (busyRef.current) return;
    busyRef.current = true;
    const next = dir === 'next'
      ? (current + 1) % NEWS.length
      : (current - 1 + NEWS.length) % NEWS.length;
    const outAnim = dir === 'next' ? 'nr-out-left' : 'nr-out-right';
    const inAnim  = dir === 'next' ? 'nr-in-right' : 'nr-in-left';
    setAnim(`${outAnim} ${ANIM_DUR}ms ease-in forwards`);
    setTimeout(() => {
      setCurrent(next);
      setAnim(`${inAnim} ${ANIM_DUR}ms ease-out forwards`);
      setTimeout(() => { setAnim(null); busyRef.current = false; }, ANIM_DUR);
    }, ANIM_DUR);
  };

  const handleClose = () => {
    setAnim('nr-fold 380ms cubic-bezier(.4,0,.2,1) forwards');
    setTimeout(onClose, 360);
  };

  const onTouchStart = (e) => { touchStartX.current = e.changedTouches[0].clientX; };
  const onTouchEnd   = (e) => {
    if (touchStartX.current === null) return;
    const diff = touchStartX.current - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 50) go(diff > 0 ? 'next' : 'prev');
    touchStartX.current = null;
  };

  const art   = NEWS[current];
  const color = SRC_COLORS[art.src] || '#1a3a5c';

  return (
    <div
      onClick={handleClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(8,26,36,0.8)', backdropFilter: 'blur(7px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '32px 24px', overflowY: 'auto'
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        style={{
          background: '#F7F3E8',
          width: 'min(840px, 100%)',
          borderRadius: 2,
          boxShadow: '0 2px 4px rgba(0,0,0,0.12), 0 24px 72px rgba(0,0,0,0.38)',
          transformOrigin: 'center center',
          animation: anim || 'none',
          margin: 'auto',
          overflow: 'hidden'
        }}
      >
        {/* ── Masthead ── */}
        <div style={{ padding: '16px 32px 12px', borderBottom: '3px double #2a2a2a' }}>
          {/* Top bar: label + close */}
          <div style={{
            display: 'flex', justifyContent: 'space-between',
            alignItems: 'center', marginBottom: 12
          }}>
            <span style={{
              fontSize: 10, fontWeight: 700, letterSpacing: '0.14em',
              textTransform: 'uppercase', color: '#888',
              fontFamily: 'var(--font-mono)'
            }}>
              Pravah Solution · Press Coverage
            </span>
            <button
              onClick={handleClose}
              style={{
                border: '1px solid #ccc', background: 'transparent',
                width: 28, height: 28, borderRadius: 1, cursor: 'pointer',
                color: '#666', display: 'flex', alignItems: 'center', justifyContent: 'center'
              }}
            >
              <Icon name="x" size={13}/>
            </button>
          </div>

          {/* Publication name + date */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 8 }}>
            <div style={{
              fontFamily: 'var(--font-display)', fontWeight: 700,
              fontSize: 'clamp(22px, 4vw, 30px)', letterSpacing: '-0.02em',
              color: color, lineHeight: 1
            }}>
              {art.src}
            </div>
            <div style={{
              fontSize: 11, color: '#777', fontFamily: 'var(--font-mono)',
              letterSpacing: '0.06em', textAlign: 'right'
            }}>
              {art.date}&ensp;·&ensp;{art.min} min read
            </div>
          </div>
        </div>

        {/* ── Article body ── */}
        <div style={{ padding: '28px 32px 24px' }}>
          {/* Headline */}
          <h2 style={{
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 'clamp(22px, 3.5vw, 32px)', lineHeight: 1.12,
            letterSpacing: '-0.02em', color: '#1a1a1a', margin: '0 0 18px'
          }}>
            {art.title}
          </h2>

          {/* Thin rule */}
          <div style={{ borderTop: '1px solid #ccc', marginBottom: 18 }}/>

          {/* Pull quote / dek */}
          <p style={{
            fontSize: 16, lineHeight: 1.65, color: '#333',
            fontStyle: 'italic', margin: '0 0 20px',
            borderLeft: `3px solid ${color}`,
            paddingLeft: 16
          }}>
            {art.dek}
          </p>

          {/* Body paragraphs */}
          <p style={{ fontSize: 15, lineHeight: 1.8, color: '#444', margin: '0 0 14px' }}>
            {art.body}
          </p>
          <p style={{
            fontSize: 13, lineHeight: 1.7, color: '#888',
            margin: '0 0 24px', fontStyle: 'italic'
          }}>
            This is an excerpt. Read the full article at {art.src} for complete coverage.
          </p>

          {/* Thin rule */}
          <div style={{ borderTop: '1px solid #ccc', marginBottom: 20 }}/>

          {/* Read more link */}
          <a
            href="#"
            onClick={e => e.preventDefault()}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: 13, fontWeight: 700, color: color,
              textDecoration: 'none', letterSpacing: '0.02em',
              borderBottom: `1px solid ${color}`, paddingBottom: 2
            }}
          >
            Read full article at {art.src} &rarr;
          </a>
        </div>

        {/* ── Navigation bar ── */}
        <div style={{
          background: '#1a1a1a',
          padding: '14px 32px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between'
        }}>
          {/* Prev */}
          <button
            className="nr-nav-btn"
            onClick={() => go('prev')}
            style={{
              background: 'transparent',
              border: '1px solid rgba(244,239,224,0.25)',
              color: 'rgba(244,239,224,0.7)',
              padding: '7px 16px', borderRadius: 1,
              cursor: 'pointer', fontSize: 11, fontWeight: 700,
              letterSpacing: '0.1em', textTransform: 'uppercase',
              fontFamily: 'var(--font-mono)'
            }}
          >
            ← Prev
          </button>

          {/* Page indicator */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <div style={{ display: 'flex', gap: 6 }}>
              {NEWS.map((_, i) => (
                <button
                  key={i}
                  onClick={() => {
                    if (i === current || busyRef.current) return;
                    const dir = i > current ? 'next-to' : 'prev-to';
                    busyRef.current = true;
                    const outAnim = i > current ? 'nr-out-left' : 'nr-out-right';
                    const inAnim  = i > current ? 'nr-in-right' : 'nr-in-left';
                    setAnim(`${outAnim} ${ANIM_DUR}ms ease-in forwards`);
                    setTimeout(() => {
                      setCurrent(i);
                      setAnim(`${inAnim} ${ANIM_DUR}ms ease-out forwards`);
                      setTimeout(() => { setAnim(null); busyRef.current = false; }, ANIM_DUR);
                    }, ANIM_DUR);
                  }}
                  style={{
                    width: i === current ? 20 : 7, height: 7,
                    borderRadius: 4, border: 'none', cursor: 'pointer',
                    background: i === current ? '#F4C542' : 'rgba(244,239,224,0.25)',
                    transition: 'width 200ms, background 200ms',
                    padding: 0
                  }}
                />
              ))}
            </div>
            <span style={{
              fontFamily: 'var(--font-mono)', fontSize: 10,
              color: 'rgba(244,239,224,0.4)', letterSpacing: '0.12em'
            }}>
              {current + 1} / {NEWS.length}
            </span>
          </div>

          {/* Next */}
          <button
            className="nr-nav-btn"
            onClick={() => go('next')}
            style={{
              background: 'transparent',
              border: '1px solid rgba(244,239,224,0.25)',
              color: 'rgba(244,239,224,0.7)',
              padding: '7px 16px', borderRadius: 1,
              cursor: 'pointer', fontSize: 11, fontWeight: 700,
              letterSpacing: '0.1em', textTransform: 'uppercase',
              fontFamily: 'var(--font-mono)'
            }}
          >
            Next →
          </button>
        </div>
      </div>
    </div>
  );
};

// ── NewsCard ──────────────────────────────────────────────────────────────────
const NewsCard = ({ n, onClick }) => (
  <article
    className="news-card-inner"
    onClick={onClick}
    style={{
      display: 'grid', gridTemplateColumns: '120px 1fr', gap: 18,
      background: 'var(--paper)', border: '1px solid var(--hairline)',
      borderRadius: 4, padding: 18, cursor: 'pointer',
      transition: 'border-color 200ms var(--ease-out), box-shadow 200ms var(--ease-out)'
    }}
    onMouseEnter={e => {
      e.currentTarget.style.borderColor = 'var(--ink)';
      e.currentTarget.style.boxShadow = '0 4px 16px rgba(8,26,36,0.08)';
    }}
    onMouseLeave={e => {
      e.currentTarget.style.borderColor = 'var(--hairline)';
      e.currentTarget.style.boxShadow = 'none';
    }}
  >
    <div className="news-src-block" style={{
      background: SRC_COLORS[n.src] || '#1a3a5c', borderRadius: 2,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: SRC_COLORS[n.src] === '#c8860a' ? 'var(--ink)' : 'var(--cream)',
      fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16,
      letterSpacing: '-0.02em', padding: 12, textAlign: 'center', lineHeight: 1.2
    }}>
      {n.src}
    </div>
    <div>
      <div style={{
        fontSize: 11, fontWeight: 600, letterSpacing: '0.1em',
        textTransform: 'uppercase', color: 'var(--gold)', marginBottom: 6
      }}>
        In the news · {n.date}
      </div>
      <h4 style={{
        fontFamily: 'var(--font-display)', fontWeight: 600,
        fontSize: 20, lineHeight: 1.2, letterSpacing: '-0.01em', margin: '0 0 6px'
      }}>
        {n.title}
      </h4>
      <p style={{ fontSize: 14, color: 'var(--stone)', lineHeight: 1.5, margin: '0 0 8px' }}>
        {n.dek}
      </p>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--stone)' }}>
        {n.min} min read · <span style={{ textDecoration: 'underline' }}>Read more →</span>
      </span>
    </div>
  </article>
);

// ── News section ──────────────────────────────────────────────────────────────
const News = () => {
  const [openIdx, setOpenIdx] = React.useState(null);

  return (
    <>
      <section id="press" className="section-pad" style={{
        background: 'var(--cream-deep)', padding: '128px 32px',
        borderTop: '1px solid var(--hairline)'
      }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            marginBottom: 40, flexWrap: 'wrap', gap: 24
          }}>
            <div>
              <Eyebrow accent>In The News</Eyebrow>
              <h2 style={{
                fontFamily: 'var(--font-display)', fontWeight: 600,
                fontSize: 'clamp(36px, 4vw, 56px)', lineHeight: 1.02,
                letterSpacing: '-0.03em', margin: '16px 0 0'
              }}>
                What the press is writing.
              </h2>
            </div>
            <Button variant="ghost" arrow onClick={() => setOpenIdx(0)}>All press coverage</Button>
          </div>

          <div className="grid-2" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
            {NEWS.map((n, i) => (
              <NewsCard key={i} n={n} onClick={() => setOpenIdx(i)}/>
            ))}
          </div>
        </div>
      </section>

      {openIdx !== null && (
        <NewsReader
          startIndex={openIdx}
          onClose={() => setOpenIdx(null)}
        />
      )}
    </>
  );
};

window.News = News;
