/* Endorsements screen — name + affiliation.
   Approved endorsements load from Supabase (table: endorsements, status='approved').
   The hardcoded list below is a fallback if Supabase is unreachable. Public
   submissions are inserted as status='pending' and only appear after an admin
   approves them in /admin. */

const { useState: useStateEnd, useEffect: useEffectEnd } = React;

/* Fallback only — the live list comes from Supabase. Keep roughly in sync. */
const FALLBACK_ENDORSEMENTS = [
  { name: 'Paula Lonergren',        role: '' },
  { name: 'Scott Lester',           role: 'PNW Water Heaters' },
  { name: 'Wayne Hansen',           role: 'Wind Walker Express, Owner' },
  { name: 'Matt Woodruff',          role: 'Take Charge Electric' },
  { name: 'Matt Lester',            role: 'All Round Gutters and Roof Top Services' },
  { name: 'Todd Hansen',            role: 'Wind Walker Express, President' },
  { name: 'Bob Black',              role: 'Retired Fire Chief' },
  { name: 'Patrick Firman',         role: 'The Floatation Device' },
  { name: 'Paul Wicklund',          role: 'MultiWire Inc' },
  { name: 'John & Carole Holmas',   role: 'JC Enterprises' },
  { name: 'Gary Parker',            role: 'BB2U' },
  { name: 'Ed Robinson',            role: '' },
  { name: 'Kim Richardson',         role: '' },
  { name: 'Bryan Duncan',           role: '' },
  { name: 'Lewis Richardson',       role: '' },
  { name: 'Gary Hiller',            role: '' },
  { name: 'Kelly Busey',            role: 'Retired Police Chief' },
];

/* Endorsements hero — same Tacoma Narrows Bridge backdrop + dark-left gradient
   as the Solutions hero (shares responsive rules via the .endorsements-hero
   selectors added alongside .issues-hero in index.html). */
const EndorsementsHero = () => (
  <section className="section endorsements-hero" style={{
    position: 'relative',
    minHeight: 'min(72vh, 600px)',
    overflow: 'hidden',
    borderBottom: '1px solid var(--divider)',
    background: 'var(--color-ink)',
    color: '#fff',
    display: 'flex',
    alignItems: 'stretch',
  }}>
    <img
      className="endorsements-hero-img"
      src="assets/hero-bridge.png"
      alt="Tacoma Narrows Bridge at sunset over Pierce County"
      style={{
        position: 'absolute', inset: 0,
        width: '100%', height: '100%',
        objectFit: 'cover',
        objectPosition: 'center center',
        display: 'block',
      }}
    />
    <div className="endorsements-hero-overlay" aria-hidden="true" style={{
      position: 'absolute', inset: 0,
      background:
        'linear-gradient(90deg, rgba(8, 12, 24, 0.92) 0%, rgba(8, 12, 24, 0.85) 22%, rgba(8, 12, 24, 0.55) 48%, rgba(8, 12, 24, 0.20) 72%, rgba(8, 12, 24, 0.05) 100%)',
    }} />
    <div className="endorsements-hero-inner" style={{
      position: 'relative',
      width: '100%',
      maxWidth: 1160,
      margin: '0 auto',
      padding: '120px 32px 96px',
      display: 'flex',
      alignItems: 'center',
    }}>
      <div style={{ maxWidth: 640 }}>
        <span aria-hidden="true" style={{
          display: 'block', width: 56, height: 2,
          background: 'var(--color-gold-base)',
          marginBottom: 24,
        }} />
        <div style={{
          fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700,
          letterSpacing: '0.22em', textTransform: 'uppercase',
          color: 'var(--color-gold-300)',
          marginBottom: 26,
        }}>
          Endorsements
        </div>
        <h1 style={{
          margin: '0 0 28px',
          fontFamily: 'var(--font-display)',
          fontWeight: 800,
          fontSize: 'clamp(2.4rem, 5vw, 4rem)',
          lineHeight: 1.04,
          letterSpacing: '-0.022em',
          color: '#fff',
          maxWidth: '14ch',
          textShadow: '0 2px 28px rgba(0,0,0,0.45)',
        }}>
          Pierce County is with Chuck.
        </h1>
        <p style={{
          margin: 0,
          fontFamily: 'var(--font-serif)',
          fontStyle: 'italic',
          fontSize: 'clamp(1.05rem, 1.4vw, 1.2rem)',
          lineHeight: 1.55,
          color: 'rgba(255,255,255,0.94)',
          maxWidth: '54ch',
          textShadow: '0 1px 18px rgba(0,0,0,0.5)',
        }}>
          Small business owners, first responders, and neighbors who have watched
          Chuck do the work for 34 years &mdash; and who are standing with him now.
        </p>
      </div>
    </div>
  </section>
);

/* Submission modal — inserts a pending endorsement. Nothing goes live until an
   admin approves it in /admin. */
function EndorseModal({ onClose }) {
  const [name, setName] = useStateEnd('');
  const [role, setRole] = useStateEnd('');
  const [email, setEmail] = useStateEnd('');
  const [busy, setBusy] = useStateEnd(false);
  const [done, setDone] = useStateEnd(false);
  const [err, setErr] = useStateEnd('');
  const [honeypot, setHoneypot] = useStateEnd('');
  const [openedAt, setOpenedAt] = useStateEnd(0);
  useEffectEnd(() => { setOpenedAt(Date.now()); }, []);

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    // Spam traps: hidden field + too-fast submit are silently treated as success.
    if (honeypot) { setDone(true); return; }
    if (Date.now() - openedAt < 2000) { setDone(true); return; }
    if (!name.trim()) { setErr('Please enter your name.'); return; }
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setErr('Please enter a valid email so we can confirm.'); return; }

    if (!window.supabaseClient) { setErr('Connection issue. Please try again.'); return; }

    setBusy(true);
    const { error } = await window.supabaseClient
      .from('endorsements')
      .insert({
        name: name.trim(),
        role: role.trim() || null,
        email: email.trim().toLowerCase(),
        source: 'site_endorse_form',
      });
    setBusy(false);
    if (error) {
      console.error('[endorsement insert]', error);
      setErr('Something went wrong. Please try again.');
      return;
    }
    setDone(true);
  };

  return (
    <div
      onClick={onClose}
      role="dialog" aria-modal="true" aria-labelledby="endorse-title"
      style={{
        position: 'fixed', inset: 0, zIndex: 300,
        background: 'rgba(7, 24, 4, 0.55)',
        backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20, animation: 'fadeInUp 200ms var(--ease-standard) both',
      }}>
      <div
        onClick={e => e.stopPropagation()}
        style={{
          position: 'relative', background: '#fff', borderRadius: 6,
          width: '100%', maxWidth: 520, padding: '40px 40px 34px',
          borderTop: '4px solid var(--color-gold-base)',
          boxShadow: '0 30px 80px rgba(7, 24, 4, 0.32)',
          animation: 'fadeInUp 280ms var(--ease-standard) both',
        }}>
        <button
          onClick={onClose} aria-label="Close"
          style={{
            position: 'absolute', top: 14, right: 16, background: 'none',
            border: 'none', cursor: 'pointer', fontSize: 26, lineHeight: 1,
            color: 'var(--color-ink-soft)', padding: 8,
          }}>×</button>

        {done ? (
          <>
            <div style={{
              fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700,
              letterSpacing: '0.18em', textTransform: 'uppercase',
              color: 'var(--brand-accent-warm)',
            }}>Thank you</div>
            <h2 id="endorse-title" className="h2" style={{ margin: '12px 0 14px', fontSize: 28, lineHeight: 1.15 }}>
              Your endorsement is in.
            </h2>
            <p style={{ fontFamily: 'var(--font-serif)', fontSize: 17, lineHeight: 1.55, color: 'var(--color-ink-soft)', margin: '0 0 24px' }}>
              Thanks for standing with Chuck. The campaign reviews every endorsement before
              it&rsquo;s posted, so your name will appear on this page shortly.
            </p>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button variant="primary" onClick={onClose}>Done</Button>
            </div>
          </>
        ) : (
          <>
            <div style={{
              fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700,
              letterSpacing: '0.18em', textTransform: 'uppercase',
              color: 'var(--brand-accent-warm)',
            }}>Endorse Chuck West</div>
            <h2 id="endorse-title" className="h2" style={{ margin: '12px 0 6px', fontSize: 28, lineHeight: 1.15 }}>
              Add your name.
            </h2>
            <p style={{ fontFamily: 'var(--font-serif)', fontSize: 16, lineHeight: 1.5, color: 'var(--color-ink-soft)', margin: '0 0 22px' }}>
              We review each submission before posting it, so your name appears after the
              campaign confirms it. Your email stays private.
            </p>
            <form onSubmit={submit} className="field" style={{ display: 'grid', gap: 16 }}>
              {/* Honeypot */}
              <input
                type="text" name="company" tabIndex={-1} autoComplete="off"
                value={honeypot} onChange={e => setHoneypot(e.target.value)} aria-hidden="true"
                style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }}
              />
              <div>
                <label htmlFor="en-name">Name *</label>
                <input id="en-name" type="text" value={name} onChange={e => setName(e.target.value)} required placeholder="Your full name" />
              </div>
              <div>
                <label htmlFor="en-role">Affiliation <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 400 }}>(optional, shown publicly)</span></label>
                <input id="en-role" type="text" value={role} onChange={e => setRole(e.target.value)} placeholder="e.g. business name, or title" />
              </div>
              <div>
                <label htmlFor="en-email">Email * <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 400 }}>(private)</span></label>
                <input id="en-email" type="email" value={email} onChange={e => setEmail(e.target.value)} required placeholder="your@email.com" />
              </div>
              {err && <div style={{ fontSize: 13, color: '#9b1c1c' }}>{err}</div>}
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 4 }}>
                <Button variant="quiet" type="button" onClick={onClose}>Cancel</Button>
                <Button variant="primary" type="submit" disabled={busy}>
                  {busy ? 'Submitting…' : 'Submit endorsement'}
                </Button>
              </div>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

const EndorsementsScreen = ({ onNavigate }) => {
  const [list, setList] = useStateEnd(FALLBACK_ENDORSEMENTS);
  const [modalOpen, setModalOpen] = useStateEnd(false);

  useEffectEnd(() => {
    let alive = true;
    (async () => {
      if (!window.supabaseClient) return;
      const { data, error } = await window.supabaseClient
        .from('endorsements')
        .select('name, role')
        .eq('status', 'approved')
        .order('sort_order', { ascending: true, nullsFirst: false })
        .order('created_at', { ascending: true });
      if (!alive) return;
      if (!error && Array.isArray(data) && data.length) {
        setList(data.map(d => ({ name: d.name, role: d.role || '' })));
      }
    })();
    return () => { alive = false; };
  }, []);

  useEffectEnd(() => {
    if (!modalOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setModalOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [modalOpen]);

  return (
    <>
      <EndorsementsHero />

      <section className="section" style={{ padding: '96px 32px 128px', background: 'var(--color-paper)' }}>
        <div style={{ maxWidth: 1160, margin: '0 auto' }}>

          {/* Add-your-name callout — boxed, tinted, sits above the list */}
          <Reveal
            className="endorse-cta"
            style={{
              background: 'var(--color-green-100)',
              border: '1px solid var(--divider)',
              borderTop: '3px solid var(--color-gold-base)',
              borderRadius: 6,
              padding: '38px 40px',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              gap: 36, flexWrap: 'wrap',
              marginBottom: 72,
            }}
          >
            <div style={{ maxWidth: '56ch' }}>
              <Eyebrow>Join them</Eyebrow>
              <h2 className="h2" style={{ margin: '10px 0 12px' }}>
                Add your name to the list.
              </h2>
              <p className="body" style={{ margin: 0 }}>
                An endorsement from someone who actually knows Pierce County carries
                more weight than any ad. If Chuck has shown up for you &mdash; on a fire
                scene, at a school board meeting, on a job site, or at a neighbor&rsquo;s
                kitchen table &mdash; say so publicly. Business owners, first responders,
                and longtime neighbors are all welcome to stand with him.
              </p>
            </div>
            <div style={{ flexShrink: 0 }}>
              <Button variant="primary" onClick={() => setModalOpen(true)}>
                Endorse Chuck &nbsp;&rsaquo;
              </Button>
            </div>
          </Reveal>

          {/* List heading */}
          <div style={{ marginBottom: 40 }}>
            <Eyebrow>Standing with Chuck</Eyebrow>
            <h2 className="h2" style={{ margin: '10px 0 0' }}>
              People who know the work.
            </h2>
          </div>

          <div className="grid-3">
            {list.map((e, i) => (
              <Reveal
                key={e.name + i}
                delay={Math.min(i * 40, 320)}
                style={{
                  background: '#fff',
                  border: '1px solid var(--divider)',
                  borderTop: '2px solid var(--color-gold-base)',
                  borderRadius: 4,
                  padding: '22px 24px',
                  display: 'flex', flexDirection: 'column', gap: 6,
                  minHeight: 96, justifyContent: 'center',
                }}
              >
                <div style={{
                  fontFamily: 'var(--font-display)', fontSize: '1.2rem',
                  fontWeight: 700, lineHeight: 1.2, letterSpacing: '-0.01em',
                  color: 'var(--color-ink)',
                }}>
                  {e.name}
                </div>
                {e.role && (
                  <div style={{
                    fontFamily: 'var(--font-sans)', fontSize: 14, lineHeight: 1.4,
                    color: 'var(--color-muted)',
                  }}>
                    {e.role}
                  </div>
                )}
              </Reveal>
            ))}
          </div>

        </div>
      </section>

      {modalOpen && <EndorseModal onClose={() => setModalOpen(false)} />}
    </>
  );
};

Object.assign(window, { EndorsementsScreen });
