/* global React, ReactDOM, RETAILERS, CAT_TINT, DEALS,
   useTweaks, TweaksPanel, TweakSection, TweakSlider, TweakToggle, TweakRadio, TweakSelect, TweakColor */

const { useState, useEffect, useMemo, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "regular",
  "accent": "#c2a753",
  "showSparklines": true,
  "showHotBadges": true,
  "compactSidebar": false,
  "monoNumerics": true
}/*EDITMODE-END*/;

// ─── Iconography (no emoji; small, original glyphs) ─────────────────────────
const Star = ({ size = 14, color = 'currentColor', filled = true, strokeWidth = 1.4 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
    <path d="M12 2.5l2.7 6.3 6.8.6-5.2 4.5 1.6 6.6L12 16.8 6.1 20.5l1.6-6.6-5.2-4.5 6.8-.6L12 2.5z"
      fill={filled ? color : 'none'} stroke={color} strokeWidth={strokeWidth} strokeLinejoin="round" />
  </svg>
);
const SparkStar = ({ size = 10, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill={color}>
    <path d="M8 0 L9.2 6.8 L16 8 L9.2 9.2 L8 16 L6.8 9.2 L0 8 L6.8 6.8 Z" />
  </svg>
);
const IconSearch = ({ size = 15 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
    <circle cx="11" cy="11" r="6.5"/><path d="M16 16l4 4"/>
  </svg>
);
const IconChevron = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
    <path d="M6 9l6 6 6-6"/>
  </svg>
);
const IconArrow = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
    <path d="M5 12h14M13 6l6 6-6 6"/>
  </svg>
);
const IconBarcode = ({ size = 13 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
    <path d="M3 5v14M6 5v14M9 5v14M12 5v14M16 5v14M19 5v14M22 5v14"/>
  </svg>
);
const IconShare = ({ size = 13 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 12v7a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-7"/><path d="M16 6l-4-4-4 4"/><path d="M12 2v14"/>
  </svg>
);
const IconBookmark = ({ size = 13, filled = false }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.6">
    <path d="M6 3h12v18l-6-4-6 4V3z"/>
  </svg>
);
const IconFilter = ({ size = 13 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
    <path d="M3 5h18M6 12h12M10 19h4"/>
  </svg>
);
const IconBell = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
    <path d="M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8z"/><path d="M10 21a2 2 0 0 0 4 0"/>
  </svg>
);
const IconLightning = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M13 2L3 14h7l-1 8 10-12h-7l1-8z"/>
  </svg>
);

// ─── Star Monitors logo (real SM monogram from brand assets) ────────────────
const StarLogo = ({ height = 36 }) => (
  <img src="assets/sm-mark.png" alt="Star Monitors" style={{ height, width: height, display: 'block', borderRadius: 6, objectFit: 'cover' }}/>
);

// ─── Product thumbnail — uses real image with swatch fallback ───────────────
const Thumb = ({ cat, sku, size, img }) => {
  const tint = CAT_TINT[cat] || ['#666', '#222'];
  const seed = parseInt(sku.slice(-3), 10) || 0;
  const angle = (seed * 7) % 360;
  const [failed, setFailed] = useState(!img);

  if (!failed && img) {
    return (
      <div style={{
        width: size, height: size, borderRadius: 8, overflow: 'hidden',
        background: '#f4f0e6', border: '1px solid rgba(255,255,255,0.06)',
        flexShrink: 0, position: 'relative',
      }}>
        <img src={img} alt={cat} loading="lazy" onError={() => setFailed(true)}
             style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }}/>
      </div>
    );
  }
  // Fallback: tinted swatch with category label
  return (
    <div style={{
      width: size, height: size, borderRadius: 8, position: 'relative', overflow: 'hidden',
      background: `linear-gradient(${angle}deg, ${tint[0]} 0%, ${tint[1]} 100%)`,
      border: '1px solid rgba(255,255,255,0.06)',
      flexShrink: 0,
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'repeating-linear-gradient(45deg, transparent 0 6px, rgba(255,255,255,0.04) 6px 7px)',
      }}/>
      <div style={{
        position: 'absolute', left: 6, bottom: 5, fontSize: 8.5, fontWeight: 600,
        color: 'rgba(255,255,255,0.85)', letterSpacing: '0.06em', textTransform: 'uppercase',
        fontFamily: 'var(--mono)',
      }}>{cat}</div>
      <div style={{
        position: 'absolute', right: 6, top: 5, fontSize: 7.5,
        color: 'rgba(255,255,255,0.45)', fontFamily: 'var(--mono)',
      }}>#{sku.slice(-4)}</div>
    </div>
  );
};

// ─── Sparkline (discount trajectory over time) ──────────────────────────────
const Sparkline = ({ data, color = '#c2a753', width = 56, height = 18 }) => {
  if (!data || !data.length) return null;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * (width - 2) + 1;
    const y = height - 1 - ((v - min) / range) * (height - 2);
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  });
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <polyline points={pts.join(' ')} fill="none" stroke={color} strokeWidth="1.3" strokeLinejoin="round" strokeLinecap="round" opacity="0.9"/>
      <circle cx={pts[pts.length-1].split(',')[0]} cy={pts[pts.length-1].split(',')[1]} r="1.8" fill={color}/>
    </svg>
  );
};

// ─── Live "pulse" indicator ─────────────────────────────────────────────────
const LivePulse = ({ color = '#5fb87c' }) => (
  <span style={{ position: 'relative', display: 'inline-block', width: 8, height: 8 }}>
    <span style={{
      position: 'absolute', inset: 0, borderRadius: '50%', background: color,
      animation: 'sm-pulse 1.8s ease-out infinite',
    }}/>
    <span style={{ position: 'absolute', inset: 2, borderRadius: '50%', background: color }}/>
  </span>
);

// ─── Odometer — split-flap / scrolling digit display ─────────────────────────
const Odometer = ({ value, size = 16, color = '#c2a753' }) => {
  const str = (value || 0).toLocaleString();
  const digitH = size * 1.2;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 0,
      fontFamily: 'var(--mono)', fontSize: size, fontWeight: 600, color,
      fontVariantNumeric: 'tabular-nums', lineHeight: 1,
    }}>
      {str.split('').map((ch, i) => {
        if (!/\d/.test(ch)) {
          return <span key={i} style={{ padding: '0 1px' }}>{ch}</span>;
        }
        const d = parseInt(ch, 10);
        return (
          <span key={i} style={{
            display: 'inline-block', overflow: 'hidden', height: digitH, width: size * 0.62,
            position: 'relative', verticalAlign: 'middle',
          }}>
            <span style={{
              display: 'flex', flexDirection: 'column',
              transform: `translateY(-${d * digitH}px)`,
              transition: 'transform .55s cubic-bezier(.65,0,.35,1)',
            }}>
              {[0,1,2,3,4,5,6,7,8,9].map(n => (
                <span key={n} style={{ height: digitH, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{n}</span>
              ))}
            </span>
          </span>
        );
      })}
    </span>
  );
};

// ─── Filter pill checkbox row ───────────────────────────────────────────────
const FilterRow = ({ label, count, checked, onChange }) => (
  <label style={{
    display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
    fontSize: 13, color: 'var(--fg)', cursor: 'default', borderRadius: 8,
    background: checked ? 'rgba(194,167,83,0.08)' : 'transparent',
  }}>
    <span style={{
      width: 16, height: 16, borderRadius: 4, border: `1.5px solid ${checked ? '#c2a753' : 'rgba(255,255,255,0.28)'}`,
      background: checked ? '#c2a753' : 'transparent', flexShrink: 0, position: 'relative',
    }}>
      {checked && <svg width="16" height="16" viewBox="0 0 12 12" style={{ position: 'absolute', inset: -1 }}>
        <path d="M3 6.5l2 2 4-4" stroke="#0d0c0c" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>}
    </span>
    <span style={{ flex: 1, fontWeight: 500 }}>{label}</span>
    {count != null && <span style={{ color: 'var(--muted)', fontFamily: 'var(--mono)', fontSize: 11 }}>{count}</span>}
    <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)} style={{ display: 'none' }}/>
  </label>
);

// ─── Sidebar ────────────────────────────────────────────────────────────────
const Sidebar = ({ t, retailer, filters, setFilters, savedCount, drawerOpen, onCloseDrawer }) => {
  const r = RETAILERS.find(x => x.id === retailer);
  const baseCount = r ? r.count : 0;
  const [liveCount, setLiveCount] = React.useState(baseCount);

  // Reset to retailer's base when the tab changes
  React.useEffect(() => { setLiveCount(baseCount); }, [baseCount]);

  // Auto-tick: simulate new deals coming in every ~1.8s
  React.useEffect(() => {
    const id = setInterval(() => {
      setLiveCount(c => c + Math.floor(Math.random() * 3) + 1);
    }, 1800);
    return () => clearInterval(id);
  }, [retailer]);

  return (
    <React.Fragment>
    {drawerOpen && <div className="sm-aside-backdrop" onClick={onCloseDrawer}/>}
    <aside className={`sm-aside ${drawerOpen ? 'open' : ''}`} style={{
      width: 248, flexShrink: 0, padding: '20px 18px 18px',
      borderRight: '1px solid var(--border)', display: 'flex', flexDirection: 'column',
      gap: 22, background: 'var(--panel)', height: '100vh', overflowY: 'auto', overflowX: 'hidden',
    }}>
      {/* Brand */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '2px 2px 14px',
        borderBottom: '1px solid var(--border)',
      }}>
        <StarLogo height={32}/>
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1, minWidth: 0 }}>
          <span style={{ fontSize: 14.5, fontWeight: 700, letterSpacing: '-0.01em', color: 'var(--fg)' }}>
            Star <span style={{ color: 'var(--gold)' }}>Monitors</span>
          </span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--muted)', letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 4 }}>
            Retail · Live Feed
          </span>
        </div>
      </div>

      {/* Tracked deals + uptime */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 2px',
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--muted)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>Tracked deals</span>
          <Odometer value={liveCount} size={18} color="var(--gold)"/>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'flex-end' }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--muted)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>Uptime</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 12.5, color: 'var(--fg)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <LivePulse/> 99.97%
          </span>
        </div>
      </div>

      {/* Account block */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <button className="sm-btn sm-btn-primary">
          Sign in
        </button>
        <button className="sm-btn sm-btn-gold">
          <IconBookmark size={11} filled/> Saved deals
          <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 11 }}>{savedCount}</span>
        </button>
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <IconFilter/>
          <span style={{ fontSize: 10.5, color: 'var(--muted)', letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'var(--mono)' }}>Filters</span>
          <button style={{
            marginLeft: 'auto', background: 'transparent', border: 0, color: 'var(--gold)',
            fontSize: 10.5, fontFamily: 'var(--mono)', letterSpacing: '0.1em', textTransform: 'uppercase', cursor: 'default',
          }}>Reset</button>
        </div>

        <div className="sm-select">
          <span>State <span style={{ color: 'var(--muted)' }}>· All 50</span></span><IconChevron/>
        </div>
        <div className="sm-select">
          <span>City <span style={{ color: 'var(--muted)' }}>· Any</span></span><IconChevron/>
        </div>
        <div className="sm-select">
          <span>Stores <span style={{ color: 'var(--muted)' }}>· All</span></span><IconChevron/>
        </div>
        <div className="sm-select">
          <span>All categories</span><IconChevron/>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <div className="sm-input" style={{ flex: 1, minWidth: 0 }}><input placeholder="Min $" type="text" style={{ minWidth: 0, width: '100%' }}/></div>
          <div className="sm-input" style={{ flex: 1, minWidth: 0 }}><input placeholder="Max $" type="text" style={{ minWidth: 0, width: '100%' }}/></div>
        </div>
        <div className="sm-select">
          <span>Discount: 35%+</span><IconChevron/>
        </div>
        <div className="sm-select">
          <span>Added: Last 24h</span><IconChevron/>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 0, marginTop: 4 }}>
          <FilterRow label="Price drops"  count="9,043"  checked={filters.priceDrop} onChange={(v)=>setFilters({...filters, priceDrop:v})} />
          <FilterRow label="Restocks"     count="2,287"  checked={filters.restock}   onChange={(v)=>setFilters({...filters, restock:v})} />
          <FilterRow label="Clearance"    count="42,118" checked={filters.clearance} onChange={(v)=>setFilters({...filters, clearance:v})} />
        </div>
      </div>

      {/* Discord footer card */}
      <a href="https://discord.gg/NGc2eaUPBp" className="sm-btn" style={{
        background: '#5865f2', color: '#fff', border: '1px solid transparent',
        textDecoration: 'none', fontWeight: 600, height: 38, fontSize: 12.5,
        marginTop: 'auto',
        boxShadow: '0 1px 0 rgba(255,255,255,0.18) inset, 0 6px 16px rgba(88,101,242,0.20)',
      }}>
        <svg width="16" height="12" viewBox="0 -28.5 256 256" fill="currentColor"><path d="M216.856 16.6c-16.572-7.754-34.29-13.388-52.815-16.597-2.275 4.113-4.933 9.646-6.766 14.047-19.692-2.962-39.203-2.962-58.533 0C96.911 9.645 94.193 4.113 91.897 0 73.353 3.209 55.613 8.864 39.042 16.638 5.618 67.147-3.443 116.401 1.087 164.956c22.169 16.555 43.653 26.611 64.775 33.193 5.215-7.178 9.866-14.808 13.873-22.849-7.631-2.9-14.94-6.478-21.846-10.632 1.832-1.358 3.624-2.777 5.356-4.237 42.122 19.703 87.89 19.703 129.51 0 1.752 1.46 3.544 2.879 5.356 4.237-6.926 4.175-14.255 7.753-21.886 10.654 4.007 8.02 8.638 15.67 13.873 22.848 21.142-6.581 42.646-16.638 64.815-33.214 5.316-56.288-9.08-105.09-38.055-148.359zM85.474 135.095c-12.645 0-23.015-11.805-23.015-26.18 0-14.376 10.149-26.2 23.015-26.2 12.867 0 23.236 11.804 23.015 26.2.02 14.375-10.148 26.18-23.015 26.18zm85.051 0c-12.645 0-23.015-11.805-23.015-26.18 0-14.376 10.148-26.2 23.015-26.2 12.867 0 23.236 11.804 23.015 26.2 0 14.375-10.148 26.18-23.015 26.18z"/></svg>
        Join the Discord
      </a>

      {/* Footer / legal box */}
      <div style={{
        padding: '10px 12px', borderRadius: 8,
        background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column', gap: 6,
      }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 10px', fontSize: 10.5, color: 'var(--muted)', fontFamily: 'var(--mono)' }}>
          <a style={{ color: 'inherit', textDecoration: 'none' }}>Privacy</a>
          <span>·</span>
          <a style={{ color: 'inherit', textDecoration: 'none' }}>Terms</a>
          <span>·</span>
          <a style={{ color: 'inherit', textDecoration: 'none' }}>About</a>
        </div>
        <a style={{ fontSize: 10.5, color: 'var(--fg)', fontFamily: 'var(--mono)', fontWeight: 600, textDecoration: 'none' }}>Do Not Sell/Share (CCPA)</a>
        <div style={{ fontSize: 9.5, color: 'var(--muted-2)', fontFamily: 'var(--mono)', marginTop: 2 }}>© 2026 Star Monitors</div>
      </div>
    </aside>
    </React.Fragment>
  );
};

window.SM_Components = { Star, SparkStar, IconSearch, IconChevron, IconArrow, IconBarcode, IconShare, IconBookmark, IconFilter, IconBell, IconLightning, StarLogo, Thumb, Sparkline, LivePulse, Odometer, FilterRow, Sidebar };
