// IndiaFloor.jsx — "The India Floor" interactive map.
// Full-bleed dark section. India outline + pulsing pins for every active
// position. Hover a pin to see the campaign card. Filter chips by industry.
// A live counter strip across the top.

// Lat/Lng → SVG coords. ViewBox is 800x900.
// Longitude 68°E (x=0) to 97°E (x=800). Latitude 37°N (y=0) to 8°N (y=900).
const lngToX = (lng) => ((lng - 68) / 29) * 800;
const latToY = (lat) => ((37 - lat) / 29) * 900;

// Stylised India outline — hand-traced, low-poly. Not geographically precise.
// Powder's brand voice is "broadsheet not SaaS"; the rough silhouette is fine.
const INDIA_PATH = [
  [74, 35], [76, 35.5], [78, 35], [80, 34.2], [82, 32], [84, 30.5],
  [86, 28], [88, 27], [90, 27.5], [92, 27.2], [94, 28], [95, 27], [97, 27.5],
  [95.5, 25], [94, 23.5], [92, 22.5], [89.5, 22], [88, 21.5], [87, 20.8],
  [85, 19.5], [82, 17], [80.5, 14], [80, 11.5], [78, 8.5], [77, 8],
  [76, 9.5], [75, 12], [74, 14], [73, 16.5], [72.5, 19.5], [71, 21],
  [70, 22], [68.5, 23], [68, 24], [69.5, 25.5], [70.5, 28], [72, 28.5],
  [74, 30.5], [75, 32.5], [76, 34], [74.5, 35], [74, 35],
];
const INDIA_D = INDIA_PATH
  .map(([lng, lat], i) => `${i === 0 ? 'M' : 'L'} ${lngToX(lng).toFixed(1)} ${latToY(lat).toFixed(1)}`)
  .join(' ') + ' Z';

// The book — every active position. Anonymised. Real-feeling numbers.
const POSITIONS = [
  { code: 'HC-04', industry: 'Healthcare',  city: 'Pune',      lng: 73.85, lat: 18.52, spend: 180000, cpl: 1180, roas: 5.8, day: 142, status: 'profit' },
  { code: 'HC-09', industry: 'Healthcare',  city: 'Delhi',     lng: 77.20, lat: 28.61, spend: 240000, cpl:  980, roas: 5.2, day:  72, status: 'profit' },
  { code: 'HC-11', industry: 'Healthcare',  city: 'Bengaluru', lng: 77.59, lat: 12.97, spend: 120000, cpl: 1410, roas: 4.1, day:  31, status: 'scaling' },
  { code: 'HC-13', industry: 'Healthcare',  city: 'Ahmedabad', lng: 72.57, lat: 23.02, spend:  85000, cpl: 1620, roas: 3.4, day:  18, status: 'scaling' },
  { code: 'RE-02', industry: 'Real-estate', city: 'Hyderabad', lng: 78.49, lat: 17.38, spend: 620000, cpl: 2450, roas: 7.1, day: 218, status: 'profit' },
  { code: 'RE-07', industry: 'Real-estate', city: 'Mumbai',    lng: 72.87, lat: 19.07, spend: 410000, cpl: 3140, roas: 4.7, day:  94, status: 'profit' },
  { code: 'RE-10', industry: 'Real-estate', city: 'Pune',      lng: 73.85, lat: 18.52, spend: 280000, cpl: 2890, roas: 4.2, day:  46, status: 'scaling' },
  { code: 'RE-12', industry: 'Real-estate', city: 'Jaipur',    lng: 75.78, lat: 26.91, spend: 150000, cpl: 4120, roas: 2.8, day:  12, status: 'watch' },
  { code: 'EDU-03',industry: 'Coaching',    city: 'Bengaluru', lng: 77.59, lat: 12.97, spend:  95000, cpl:  620, roas: 3.9, day: 167, status: 'profit' },
  { code: 'EDU-05',industry: 'Coaching',    city: 'Lucknow',   lng: 80.94, lat: 26.84, spend:  60000, cpl:  540, roas: 3.4, day:  88, status: 'profit' },
  { code: 'EDU-08',industry: 'Coaching',    city: 'Indore',    lng: 75.86, lat: 22.72, spend:  72000, cpl:  710, roas: 3.1, day:  41, status: 'scaling' },
  { code: 'EDU-11',industry: 'Coaching',    city: 'Kochi',     lng: 76.26, lat:  9.93, spend:  48000, cpl:  890, roas: 2.6, day:  22, status: 'scaling' },
  { code: 'B2B-01',industry: 'B2B services',city: 'Surat',     lng: 72.83, lat: 21.17, spend: 165000, cpl: 3820, roas: 6.4, day: 196, status: 'profit' },
  { code: 'B2B-04',industry: 'B2B services',city: 'Chennai',   lng: 80.27, lat: 13.08, spend: 220000, cpl: 4250, roas: 5.1, day: 112, status: 'profit' },
  { code: 'B2B-06',industry: 'B2B services',city: 'Kolkata',   lng: 88.36, lat: 22.57, spend: 140000, cpl: 4880, roas: 3.2, day:  58, status: 'scaling' },
  { code: 'B2B-08',industry: 'B2B services',city: 'Chandigarh',lng: 76.78, lat: 30.73, spend:  90000, cpl: 5210, roas: 2.4, day:  19, status: 'watch' },
  { code: 'B2B-09',industry: 'B2B services',city: 'Nagpur',    lng: 79.08, lat: 21.14, spend:  75000, cpl: 4640, roas: 2.1, day:   8, status: 'watch' },
  { code: 'D2C-02',industry: 'B2B services',city: 'Bhopal',    lng: 77.41, lat: 23.25, spend:  62000, cpl: 1980, roas: 3.7, day:  35, status: 'scaling' },
];

const STATUS_COLOR = {
  profit:  'var(--vault-500)',
  scaling: 'var(--powder-500)',
  watch:   'var(--loss-500)',
};

const FILTERS = ['All', 'Healthcare', 'Real-estate', 'Coaching', 'B2B services'];

const ifStyles = {
  section: { padding: '96px 0', background: 'var(--ink-1000)', color: 'var(--ink-0)', borderTop: '1px solid var(--border)' },
  container: { maxWidth: 'var(--container-max)', margin: '0 auto', padding: '0 var(--container-pad)' },
  head: { display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 64, alignItems: 'end', marginBottom: 48 },
  eyebrow: { fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(246,242,231,0.55)', fontWeight: 500, marginBottom: 12 },
  h: {
    fontFamily: 'var(--font-display)', fontWeight: 400,
    fontSize: 'clamp(36px, 5vw, 60px)',
    lineHeight: 0.92, letterSpacing: '-0.015em',
    textTransform: 'uppercase', margin: 0, maxWidth: '14ch',
    color: 'var(--ink-0)',
  },
  sub: { fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.55, color: 'rgba(246,242,231,0.65)', maxWidth: '44ch', margin: 0, paddingBottom: 6 },

  // The live counter strip — runs along the top of the floor.
  tape: {
    display: 'grid',
    gridTemplateColumns: 'repeat(4, 1fr)',
    border: '1px solid rgba(246,242,231,0.12)',
    borderRadius: 'var(--r-md)',
    marginBottom: 24,
    overflow: 'hidden',
  },
  tapeTile: {
    padding: '14px 18px',
    borderRight: '1px solid rgba(246,242,231,0.12)',
    display: 'flex',
    alignItems: 'baseline',
    justifyContent: 'space-between',
    gap: 12,
  },
  tapeLabel: { fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(246,242,231,0.55)' },
  tapeValue: { fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums', fontSize: 20, color: 'var(--ink-0)', letterSpacing: '-0.01em' },
  tapeLive: {
    display: 'inline-flex', alignItems: 'center', gap: 6,
    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', color: 'var(--vault-500)',
    textTransform: 'uppercase',
  },
  liveDot: {
    width: 6, height: 6, borderRadius: '50%', background: 'var(--vault-500)',
    boxShadow: '0 0 0 3px rgba(31,110,74,0.18)',
    animation: 'dpf-blink 1.4s var(--ease-out) infinite',
  },

  // Filter chips above the map.
  filters: { display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 20 },
  chip: (active) => ({
    fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 500,
    padding: '7px 14px', borderRadius: 999, cursor: 'pointer',
    background: active ? 'var(--ink-0)' : 'transparent',
    color: active ? 'var(--ink-1000)' : 'var(--ink-0)',
    border: '1px solid ' + (active ? 'var(--ink-0)' : 'rgba(246,242,231,0.24)'),
    transition: 'all 120ms var(--ease-out)',
  }),

  // The map area.
  floorWrap: { display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, alignItems: 'stretch' },
  mapBox: {
    background: '#141413',
    border: '1px solid rgba(246,242,231,0.12)',
    borderRadius: 'var(--r-md)',
    padding: 24,
    position: 'relative',
    minHeight: 580,
  },
  mapInner: {
    width: '100%', height: '100%',
    display: 'block',
    aspectRatio: '8 / 9',
  },
  mapCorner: {
    position: 'absolute',
    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em',
    color: 'rgba(246,242,231,0.40)',
    textTransform: 'uppercase',
  },
  legend: {
    display: 'flex', gap: 16, flexWrap: 'wrap',
    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em',
    color: 'rgba(246,242,231,0.55)',
    textTransform: 'uppercase',
    marginTop: 12,
  },
  legendDot: (color) => ({
    display: 'inline-block', width: 7, height: 7, borderRadius: '50%',
    background: color, marginRight: 6, verticalAlign: 'middle',
  }),

  // Right panel — the position table.
  bookBox: {
    background: '#141413',
    border: '1px solid rgba(246,242,231,0.12)',
    borderRadius: 'var(--r-md)',
    padding: '18px 0 0',
    display: 'flex',
    flexDirection: 'column',
    minHeight: 580,
  },
  bookHead: {
    padding: '0 18px 14px',
    borderBottom: '1px solid rgba(246,242,231,0.12)',
    display: 'flex',
    alignItems: 'baseline',
    justifyContent: 'space-between',
  },
  bookTitle: { fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(246,242,231,0.65)' },
  bookCount: { fontFamily: 'var(--font-mono)', fontSize: 10, color: 'rgba(246,242,231,0.40)' },
  bookList: {
    overflowY: 'auto',
    flex: 1,
    maxHeight: 540,
  },
  bookRow: (active, hovered) => ({
    padding: '12px 18px',
    borderBottom: '1px solid rgba(246,242,231,0.06)',
    display: 'grid',
    gridTemplateColumns: '64px 1fr auto',
    gap: 12,
    alignItems: 'center',
    cursor: 'pointer',
    background: (active || hovered) ? 'rgba(255,51,1,0.08)' : 'transparent',
    transition: 'background 120ms',
  }),
  bookCode: (color) => ({
    fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 600,
    letterSpacing: '0.08em',
    color: color,
    padding: '3px 6px',
    background: 'rgba(246,242,231,0.06)',
    borderRadius: 3,
    display: 'inline-block',
    textAlign: 'center',
  }),
  bookName: { fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--ink-0)', fontWeight: 500 },
  bookMeta: { fontFamily: 'var(--font-mono)', fontSize: 10, color: 'rgba(246,242,231,0.45)', letterSpacing: '0.06em', marginTop: 2 },
  bookCpl: { fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums', fontSize: 13, color: 'var(--ink-0)', textAlign: 'right' },

  // Tooltip over the map.
  tip: {
    position: 'absolute',
    pointerEvents: 'none',
    background: '#0B0B0A',
    border: '1px solid var(--powder-500)',
    borderRadius: 'var(--r-sm)',
    padding: '10px 12px',
    minWidth: 180,
    boxShadow: '0 8px 24px rgba(0,0,0,0.5)',
    zIndex: 10,
    transform: 'translate(-50%, calc(-100% - 12px))',
  },
  tipCode: { fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', color: 'var(--powder-500)', fontWeight: 600 },
  tipName: { fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--ink-0)', fontWeight: 500, marginTop: 4 },
  tipRows: { marginTop: 8, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'rgba(246,242,231,0.65)', lineHeight: 1.6 },
};

const fmtSpend = (n) => {
  if (n >= 1e7) return '₹' + (n/1e7).toFixed(2) + 'Cr';
  if (n >= 1e5) return '₹' + (n/1e5).toFixed(1) + 'L';
  return '₹' + (n/1000).toFixed(0) + 'k';
};

function IndiaFloor() {
  const [filter, setFilter] = React.useState('All');
  const [active, setActive] = React.useState(null);
  const [hovered, setHovered] = React.useState(null);
  const mapRef = React.useRef(null);

  const visible = filter === 'All'
    ? POSITIONS
    : POSITIONS.filter(p => p.industry === filter);

  // Aggregate counters
  const aggSpend = visible.reduce((s, p) => s + p.spend, 0);
  const aggLeads = visible.reduce((s, p) => s + Math.round(p.spend / p.cpl), 0);
  const medianCpl = (() => {
    const a = [...visible].map(p => p.cpl).sort((x, y) => x - y);
    return a.length ? a[Math.floor(a.length / 2)] : 0;
  })();
  const medianRoas = (() => {
    const a = [...visible].map(p => p.roas).sort((x, y) => x - y);
    return a.length ? a[Math.floor(a.length / 2)] : 0;
  })();

  // Tooltip lookup
  const tip = hovered || active;
  const tipPos = tip ? { x: lngToX(tip.lng), y: latToY(tip.lat) } : null;

  return (
    <section id="floor" style={ifStyles.section}>
      <style>{`
        @keyframes dpf-blink {
          0%, 70%  { opacity: 1; transform: scale(1); }
          85%      { opacity: 0.35; transform: scale(0.85); }
          100%     { opacity: 1; transform: scale(1); }
        }
        @keyframes dpf-pulse {
          0%   { r: 5;  opacity: 0.7; }
          70%  { r: 18; opacity: 0; }
          100% { r: 18; opacity: 0; }
        }
        .dpf-pin-pulse { animation: dpf-pulse 2.4s var(--ease-out) infinite; }
      `}</style>

      <div style={ifStyles.container}>
        <div style={ifStyles.head}>
          <div>
            <div style={ifStyles.eyebrow}>03 · The floor</div>
            <h2 style={ifStyles.h}>Every position. On a map.</h2>
          </div>
          <p style={ifStyles.sub}>
            Anonymised but real — every active campaign we're running today.
            Hover a pin or a row. Most agencies show testimonials. We show the book.
          </p>
        </div>

        {/* Live tape strip */}
        <div style={ifStyles.tape}>
          <div style={ifStyles.tapeTile}>
            <div>
              <div style={ifStyles.tapeLabel}>Open positions</div>
              <div style={ifStyles.tapeValue}>{visible.length}</div>
            </div>
            <span style={ifStyles.tapeLive}><span style={ifStyles.liveDot}/>Live</span>
          </div>
          <div style={ifStyles.tapeTile}>
            <div>
              <div style={ifStyles.tapeLabel}>Agg spend / mo</div>
              <div style={ifStyles.tapeValue}>{fmtSpend(aggSpend)}</div>
            </div>
          </div>
          <div style={ifStyles.tapeTile}>
            <div>
              <div style={ifStyles.tapeLabel}>Leads / mo</div>
              <div style={ifStyles.tapeValue}>{aggLeads.toLocaleString('en-IN')}</div>
            </div>
          </div>
          <div style={{...ifStyles.tapeTile, borderRight: 'none'}}>
            <div>
              <div style={ifStyles.tapeLabel}>Median CPL · ROAS</div>
              <div style={ifStyles.tapeValue}>₹{medianCpl.toLocaleString('en-IN')} · {medianRoas.toFixed(1)}×</div>
            </div>
          </div>
        </div>

        {/* Filters */}
        <div style={ifStyles.filters}>
          {FILTERS.map(f => (
            <button key={f} style={ifStyles.chip(filter === f)} onClick={() => { setFilter(f); setActive(null); }}>
              {f}
            </button>
          ))}
        </div>

        {/* Map + Book */}
        <div style={ifStyles.floorWrap} data-floor-wrap>
          <div style={ifStyles.mapBox} ref={mapRef}>
            <span style={{...ifStyles.mapCorner, top: 14, left: 18}}>India · 13 May 2026 · 09:42 IST</span>
            <span style={{...ifStyles.mapCorner, top: 14, right: 18}}>Source: DP internal</span>

            <svg viewBox="0 0 800 900" style={ifStyles.mapInner} preserveAspectRatio="xMidYMid meet">
              {/* Country outline */}
              <path
                d={INDIA_D}
                fill="rgba(246,242,231,0.025)"
                stroke="rgba(246,242,231,0.22)"
                strokeWidth="1.5"
                strokeLinejoin="round"
              />

              {/* Pins */}
              {visible.map((p, i) => {
                const x = lngToX(p.lng);
                const y = latToY(p.lat);
                const color = STATUS_COLOR[p.status];
                const isActive = (active?.code === p.code) || (hovered?.code === p.code);
                return (
                  <g
                    key={p.code}
                    style={{cursor: 'pointer'}}
                    onMouseEnter={() => setHovered(p)}
                    onMouseLeave={() => setHovered(null)}
                    onClick={() => setActive(active?.code === p.code ? null : p)}
                  >
                    {/* Pulse ring (only for scaling/profit; watch is solid) */}
                    {p.status !== 'watch' && (
                      <circle
                        cx={x} cy={y} r="5"
                        fill="none"
                        stroke={color}
                        strokeWidth="1.5"
                        className="dpf-pin-pulse"
                        style={{ animationDelay: `${i * 0.18}s` }}
                      />
                    )}
                    {/* Core dot */}
                    <circle cx={x} cy={y} r={isActive ? 7 : 5} fill={color} opacity="0.95" />
                    {/* Outer halo on hover */}
                    {isActive && <circle cx={x} cy={y} r="14" fill="none" stroke={color} strokeWidth="1.5" opacity="0.5" />}
                  </g>
                );
              })}
            </svg>

            {/* Tooltip — positioned over the SVG by ratio of viewBox */}
            {tip && tipPos && (
              <div
                style={{
                  ...ifStyles.tip,
                  left:  `calc(24px + (100% - 48px) * ${tipPos.x / 800})`,
                  top:   `calc(24px + (100% - 48px) * ${tipPos.y / 900})`,
                }}
              >
                <div style={ifStyles.tipCode}>{tip.code}</div>
                <div style={ifStyles.tipName}>{tip.city} · {tip.industry}</div>
                <div style={ifStyles.tipRows}>
                  Spend / mo · {fmtSpend(tip.spend)}<br/>
                  CPL · ₹{tip.cpl.toLocaleString('en-IN')}<br/>
                  ROAS · {tip.roas.toFixed(1)}×<br/>
                  Day · {tip.day}
                </div>
              </div>
            )}

            <div style={ifStyles.legend}>
              <span><span style={ifStyles.legendDot('var(--vault-500)')}/>Profitable</span>
              <span><span style={ifStyles.legendDot('var(--powder-500)')}/>Scaling</span>
              <span><span style={ifStyles.legendDot('var(--loss-500)')}/>Under floor</span>
            </div>
          </div>

          {/* The book — scrollable position list */}
          <div style={ifStyles.bookBox}>
            <div style={ifStyles.bookHead}>
              <span style={ifStyles.bookTitle}>The book · sorted by spend</span>
              <span style={ifStyles.bookCount}>{visible.length} / {POSITIONS.length}</span>
            </div>
            <div style={ifStyles.bookList}>
              {[...visible].sort((a, b) => b.spend - a.spend).map(p => (
                <div
                  key={p.code}
                  style={ifStyles.bookRow(active?.code === p.code, hovered?.code === p.code)}
                  onMouseEnter={() => setHovered(p)}
                  onMouseLeave={() => setHovered(null)}
                  onClick={() => setActive(active?.code === p.code ? null : p)}
                >
                  <span style={ifStyles.bookCode(STATUS_COLOR[p.status])}>{p.code}</span>
                  <div>
                    <div style={ifStyles.bookName}>{p.city}</div>
                    <div style={ifStyles.bookMeta}>{p.industry} · day {p.day}</div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <div style={ifStyles.bookCpl}>₹{p.cpl.toLocaleString('en-IN')}</div>
                    <div style={ifStyles.bookMeta}>{p.roas.toFixed(1)}× · {fmtSpend(p.spend)}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { IndiaFloor });
