/* generator-widget.jsx — the hero generator widget
 * Reusable across homepage + /free-poa + /[state]-poa.
 * Modes: 'compact' (sidebar) | 'hero' (full-width with map toggle)
 * Stores selection in localStorage as 'poa.draft' so the wizard resumes from it.
 */

function GeneratorWidget({
  mode = 'hero',
  defaultState = '',
  defaultType = '',
  showTrust = true,
  variant = 'card', // 'card' | 'inset'
}) {
  const [picker, setPicker] = React.useState('map'); // 'map' | 'list'
  const [stateSel, setStateSel] = React.useState(defaultState);
  const [typeSel, setTypeSel]   = React.useState(defaultType);

  const submit = () => {
    const params = new URLSearchParams();
    if (stateSel) params.set('state', stateSel);
    if (typeSel)  params.set('type', typeSel);
    try {
      localStorage.setItem('poa.draft', JSON.stringify({ state: stateSel, type: typeSel, ts: Date.now() }));
    } catch (e) {}
    window.location.href = 'generator.html' + (params.toString() ? '?' + params.toString() : '');
  };

  const valid = stateSel && typeSel;

  const wrapStyle = variant === 'inset'
    ? {
        background: 'var(--surface)',
        border: '1.5px solid var(--ink)',
        borderRadius: 'var(--r-xl)',
        padding: 'var(--s-7)',
        boxShadow: '8px 8px 0 0 var(--ink)',
      }
    : {
        background: 'var(--surface)',
        border: '1.5px solid var(--ink)',
        borderRadius: 'var(--r-xl)',
        padding: 'var(--s-8)',
        boxShadow: '8px 8px 0 0 var(--ink)',
      };

  return (
    <div className="generator-widget" style={wrapStyle}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 'var(--s-5)', flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Free POA Generator</div>
          <div style={{ fontFamily: 'Outfit', fontWeight: 600, fontSize: 22, letterSpacing: '-0.02em' }}>
            Pick your state &amp; type. We'll do the rest.
          </div>
        </div>
        <div role="tablist" aria-label="State picker mode" style={{
          display: 'inline-flex', borderRadius: 'var(--r-pill)',
          border: '1.5px solid var(--ink)', overflow: 'hidden', background: 'var(--paper)',
          padding: 3,
        }}>
          {[['map','Map'],['list','List']].map(([k, label]) => (
            <button key={k} role="tab" aria-selected={picker === k}
              onClick={() => setPicker(k)}
              style={{
                border: 'none', background: picker === k ? 'var(--ink)' : 'transparent',
                color: picker === k ? 'var(--paper)' : 'var(--ink)',
                padding: '6px 14px', borderRadius: 'var(--r-pill)', fontWeight: 600, fontSize: 13,
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
              <Icon name={k === 'map' ? 'map' : 'list'} size={14} />
              {label}
            </button>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 'var(--s-7)' }} className="gw-grid">
        {/* Left: state */}
        <div>
          <label className="eyebrow" style={{ display: 'block', marginBottom: 8 }}>1 — Your state</label>
          {picker === 'map' ? (
            <USMap value={stateSel} onChange={setStateSel} />
          ) : (
            <select className="select" value={stateSel} onChange={(e) => setStateSel(e.target.value)}>
              <option value="">Choose your state…</option>
              {US_STATES.map(([code, name]) => (
                <option key={code} value={code}>{name}</option>
              ))}
            </select>
          )}
          {stateSel && (
            <div style={{ marginTop: 10, fontSize: 13, color: 'var(--muted)' }}>
              Selected: <strong style={{ color: 'var(--ink)' }}>
                {(US_STATES.find(s => s[0] === stateSel) || [])[1] || stateSel}
              </strong>
            </div>
          )}
        </div>

        {/* Right: type */}
        <div>
          <label className="eyebrow" style={{ display: 'block', marginBottom: 8 }}>2 — POA type</label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {POA_TYPES.slice(0, 6).map(t => {
              const active = typeSel === t.id;
              return (
                <button key={t.id} type="button"
                  onClick={() => setTypeSel(t.id)}
                  style={{
                    textAlign: 'left',
                    padding: '12px 14px',
                    borderRadius: 'var(--r-md)',
                    border: '1.5px solid var(--ink)',
                    background: active ? 'var(--accent)' : 'var(--paper)',
                    color: 'var(--ink)',
                    cursor: 'pointer', fontFamily: 'inherit',
                    boxShadow: active ? '3px 3px 0 0 var(--ink)' : 'none',
                    transform: active ? 'translate(-1px,-1px)' : 'none',
                    minHeight: 60,
                    display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 2,
                  }}>
                  <span style={{ fontWeight: 700, fontSize: 14 }}>{t.name}</span>
                  <span style={{ fontSize: 11, color: 'var(--muted)', lineHeight: 1.3, fontWeight: 500 }}>
                    {t.blurb.length > 38 ? t.blurb.slice(0, 36) + '…' : t.blurb}
                  </span>
                </button>
              );
            })}
          </div>
          <button type="button" onClick={() => setTypeSel('not-sure')}
            style={{
              marginTop: 8, background: 'transparent', border: 'none',
              color: 'var(--ink)', textDecoration: 'underline', textUnderlineOffset: 3,
              cursor: 'pointer', fontWeight: 500, fontSize: 13, padding: 0, fontFamily: 'inherit',
            }}>
            Not sure which? Take the 30-sec quiz →
          </button>
        </div>
      </div>

      <hr className="rule" style={{ margin: 'var(--s-7) 0 var(--s-5)' }} />

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        {showTrust && (
          <TrustRow items={[
            'Takes 5 min',
            'No signup',
            'Files auto-delete in 1 hr',
          ]} />
        )}
        <button onClick={submit}
          className="btn primary large"
          disabled={!valid}
          style={{ opacity: valid ? 1 : 0.5, cursor: valid ? 'pointer' : 'not-allowed' }}>
          Build my POA
          <Icon name="arrow" size={18} />
        </button>
      </div>

      <style>{`
        @media (max-width: 760px) {
          .gw-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

window.GeneratorWidget = GeneratorWidget;
