// Claim preview page + Submission/Claim portal
// Exports: window.ClaimPreview, window.Portal

// ---------------------------------------------------------------------
// Form submission endpoint
// ---------------------------------------------------------------------
// The claim modal posts here when a winery submits. Until this is set
// to a real endpoint, the form will fall back to a mailto: link so
// nothing is lost.
//
// To wire up real form delivery (pick one):
//   1. Formspree — sign up at https://formspree.io, create a form,
//      paste the endpoint below. Free tier: 50 submissions/month.
//   2. Web3Forms — https://web3forms.com, free unlimited, copy the
//      access key URL.
//   3. Your own — any endpoint that accepts a JSON POST.
//
// Until then, claims will open the user's email client addressed to
// CLAIM_FALLBACK_EMAIL.
const CLAIM_ENDPOINT = '';  // e.g. 'https://formspree.io/f/xyzabc123'
const CLAIM_FALLBACK_EMAIL = '[email protected]';

/* =================================================================
   CLAIM PREVIEW
   A per-winery URL (e.g. ?page=claim&w=becker) showing an
   auto-populated profile with a prominent "claim this listing" CTA.
   This is the outreach artifact — what we email to wineries.
================================================================= */
function ClaimPreview({ onNav, wineryId }) {
  const D = window.TX_DATA;
  const w = D.wineries.find(x => x.id === wineryId) || D.wineries[0];
  const ava = D.avas.find(a => a.id === w.ava);
  const [dismissed, setDismissed] = React.useState(false);
  const [modal, setModal] = React.useState(false);

  const sources = [
    { label: 'Winery website', url: 'wineryexample.com', date: 'Apr 2026' },
    { label: 'TABC permit record', url: 'tabc.texas.gov', date: 'Current' },
    { label: 'Texas AVA Atlas', url: 'ttb.gov/ava', date: 'Federal' },
    { label: 'Google Business Profile', url: 'google.com', date: 'Apr 2026' },
  ];

  return (
    <main style={{ background: 'var(--page-bg)' }}>
      {/* OUTREACH BANNER — the hook. Dismissable but sticky above the fold. */}
      {!dismissed && (
        <div style={{
          position: 'sticky', top: 60, zIndex: 40,
          background: 'var(--accent)', color: 'var(--paper)',
          padding: '16px 24px',
          borderBottom: '1px solid rgba(0,0,0,0.15)',
        }}>
          <div className="container" style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto auto', gap: 24, alignItems: 'center' }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%',
              background: 'rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16,
            }}>✓</div>
            <div>
              <div style={{ fontFamily: 'var(--font-ui)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', opacity: 0.85, fontWeight: 600, marginBottom: 2 }}>
                Draft Profile · Unclaimed
              </div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 15 }}>
                We built this listing for <strong>{w.name}</strong> from publicly available sources.
                Claim it free to verify details, respond to reviews, and add photos.
              </div>
            </div>
            <button onClick={() => setModal(true)} className="btn"
              style={{ background: 'var(--paper)', color: 'var(--accent)', borderColor: 'var(--paper)' }}>
              Claim this listing →
            </button>
            <button onClick={() => setDismissed(true)} style={{
              background: 'transparent', border: 0, color: 'rgba(255,255,255,0.7)',
              cursor: 'pointer', fontSize: 20, padding: 4,
            }} aria-label="Dismiss">×</button>
          </div>
        </div>
      )}

      {/* Hero */}
      <div style={{ position: 'relative' }}>
        <window.Ph label="hero · pulled from winery website" aspect="21/9" style={{ aspectRatio: 'auto', height: 380 }} />
        <div style={{
          position: 'absolute', top: 24, left: 24,
          padding: '6px 12px',
          background: 'rgba(0,0,0,0.7)', color: '#fff',
          fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase',
          borderRadius: 3,
        }}>
          ◦ Auto-generated · Not yet verified
        </div>
      </div>

      <div className="container" style={{ paddingTop: 40, paddingBottom: 64 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 56, alignItems: 'start' }}>
          {/* Main */}
          <div>
            <div className="section-label">Draft Listing · {ava?.short}</div>
            <h1 className="h-display" style={{ fontSize: 'clamp(44px, 6vw, 80px)' }}>{w.name}</h1>

            <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', marginTop: 18, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              <span>{w.town.toUpperCase()}, TX</span><span>·</span>
              <span>{ava?.short} AVA</span><span>·</span>
              <span>EST. {w.founded}</span><span>·</span>
              <span>{w.acres > 0 ? `${w.acres} ACRES` : 'SOURCED FRUIT'}</span>
            </div>

            <p style={{ fontFamily: 'var(--font-body)', fontSize: 19, lineHeight: 1.55, color: 'var(--ink-soft)', marginTop: 28, maxWidth: '62ch' }}>
              <span style={{ background: 'rgba(200,160,40,0.18)', padding: '0 4px' }}>
                {w.name} is a {ava?.short} winery focusing on {w.focus.toLowerCase()}.
              </span>{' '}
              The tasting room is open to the public, with a focus on {w.tag.toLowerCase()}
              bottlings.{' '}
              <span style={{ color: 'var(--ink-mute)', fontStyle: 'italic' }}>
                (Highlighted text was auto-generated — edit when you claim.)
              </span>
            </p>

            <div style={{ marginTop: 28, padding: 20, border: '1px dashed var(--rule)', background: 'var(--paper)' }}>
              <div className="kicker" style={{ marginBottom: 10 }}>Data sources used</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontFamily: 'var(--font-ui)', fontSize: 13 }}>
                {sources.map(s => (
                  <div key={s.label} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px dotted var(--rule)' }}>
                    <span style={{ color: 'var(--ink)' }}>{s.label}</span>
                    <span style={{ color: 'var(--ink-mute)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>{s.date}</span>
                  </div>
                ))}
              </div>
              <p style={{ fontSize: 12, color: 'var(--ink-mute)', margin: '14px 0 0', fontFamily: 'var(--font-body)' }}>
                Fields flagged <span style={{ background: 'rgba(200,160,40,0.25)', padding: '0 3px' }}>yellow</span> throughout the profile were auto-generated and may need correction. Claiming this listing lets you edit them directly.
              </p>
            </div>

            <h3 className="h2" style={{ marginTop: 48, marginBottom: 18 }}>What we have so far</h3>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <InfoCell label="Tasting room" value="Open Thu–Mon" auto />
              <InfoCell label="Tasting fee" value="$25–35 est." auto />
              <InfoCell label="Reservations" value="Walk-ins welcome" auto />
              <InfoCell label="Food service" value="Unknown" missing />
              <InfoCell label="Dog policy" value={w.dogFriendly ? 'Dogs welcome outside' : 'Check with winery'} />
              <InfoCell label="Varieties grown" value={ava?.signature.slice(0,3).join(', ')} auto />
              <InfoCell label="Current vintages" value="Not yet listed" missing />
              <InfoCell label="Wine club" value="Unknown" missing />
            </div>

            <h3 className="h2" style={{ marginTop: 48, marginBottom: 18 }}>Bottles on the market</h3>
            <div style={{ padding: 28, background: 'var(--paper)', border: '1px solid var(--rule)', textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, color: 'var(--ink-soft)' }}>No bottles added yet.</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-mute)', marginTop: 6 }}>
                Claim this listing to add your current releases, tasting notes, and pricing.
              </div>
            </div>
          </div>

          {/* Claim CTA sidebar */}
          <aside style={{ position: 'sticky', top: 160 }}>
            <div style={{ padding: 28, background: 'var(--ink)', color: 'var(--paper)' }}>
              <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', opacity: 0.55, fontWeight: 600 }}>
                For the owner of {w.name}
              </div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, margin: '14px 0 16px', lineHeight: 1.15 }}>
                Claim this listing. It's free.
              </h3>
              <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 22px', fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.7 }}>
                {[
                  'Edit every field directly',
                  'Upload real photography',
                  'List current releases',
                  'Respond to reviews',
                  'Post events to our calendar',
                  'Appear in filtered searches',
                ].map(x => (
                  <li key={x} style={{ display: 'flex', gap: 10, padding: '4px 0' }}>
                    <span style={{ color: 'var(--accent)' }}>✓</span>
                    <span style={{ opacity: 0.85 }}>{x}</span>
                  </li>
                ))}
              </ul>
              <button onClick={() => setModal(true)} className="btn"
                style={{ width: '100%', justifyContent: 'center', background: 'var(--paper)', color: 'var(--ink)', borderColor: 'var(--paper)' }}>
                Claim in 2 minutes
              </button>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, opacity: 0.5, marginTop: 14, lineHeight: 1.6, textAlign: 'center' }}>
                Verified via winery domain email<br/>or TABC permit number
              </div>
            </div>

            {/* Upgrade teaser — lives above the suggest-edit card */}
            <div style={{ marginTop: 20, padding: 24, background: 'var(--paper)', border: '1px solid var(--accent)' }}>
              <div className="kicker" style={{ marginBottom: 8, color: 'var(--accent)' }}>After you claim</div>
              <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 20, margin: '0 0 8px', lineHeight: 1.2 }}>
                Want more than the basics?
              </h4>
              <p style={{ fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)', margin: '0 0 14px' }}>
                Featured ($99/mo) replaces the auto-generated draft with your story, photos, and CTAs. Premium ($299/mo) adds priority placement and an annual editorial feature.
              </p>
              <button onClick={() => onNav('plans', w.id)} className="btn btn-ghost"
                style={{ width: '100%', justifyContent: 'center', padding: '8px 14px', fontSize: 11 }}>
                See plans →
              </button>
            </div>

            <div style={{ marginTop: 20, padding: 20, background: 'var(--chip)' }}>
              <div className="kicker" style={{ marginBottom: 8 }}>Not the owner?</div>
              <p style={{ fontSize: 13, lineHeight: 1.5, margin: '0 0 10px', fontFamily: 'var(--font-body)', color: 'var(--ink-soft)' }}>
                Spot something wrong? Send a correction and we'll vet it.
              </p>
              <button className="btn btn-ghost" style={{ padding: '6px 12px', fontSize: 11, width: '100%', justifyContent: 'center' }}>
                Suggest an edit
              </button>
            </div>

            <div style={{ marginTop: 20, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-mute)', lineHeight: 1.8, letterSpacing: '0.06em' }}>
              <div>PROFILE URL</div>
              <div style={{ color: 'var(--ink)', wordBreak: 'break-all' }}>
                winesoftexas.com/w/{w.id}?preview=true
              </div>
            </div>
          </aside>
        </div>
      </div>

      {/* On successful claim, route to Plans so the winery sees the upgrade
          decision immediately — this is the conversion moment. */}
      {modal && <ClaimModal winery={w} onClose={() => setModal(false)} onSubmit={() => { setModal(false); onNav('plans', w.id); }} />}
    </main>
  );
}

function InfoCell({ label, value, auto, missing }) {
  return (
    <div style={{
      padding: '14px 16px',
      border: '1px solid var(--rule)',
      background: missing ? 'rgba(0,0,0,0.03)' : (auto ? 'rgba(200,160,40,0.08)' : 'var(--paper)'),
    }}>
      <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-mute)', marginBottom: 6, fontWeight: 600 }}>
        {label} {auto && <span style={{ color: '#b8881e' }}>· auto</span>} {missing && <span style={{ color: 'var(--ink-mute)' }}>· missing</span>}
      </div>
      <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: missing ? 'var(--ink-mute)' : 'var(--ink)', fontStyle: missing ? 'italic' : 'normal' }}>{value}</div>
    </div>
  );
}

function ClaimModal({ winery, onClose, onSubmit }) {
  const [step, setStep] = React.useState(1);
  const [method, setMethod] = React.useState('email');
  const [name, setName] = React.useState('');
  const [role, setRole] = React.useState('');
  const [contact, setContact] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    const payload = {
      winery: winery.name,
      winery_id: winery.id,
      name, role,
      verification_method: method,
      contact,
      submitted_at: new Date().toISOString(),
      source: location.href,
    };
    try {
      if (CLAIM_ENDPOINT) {
        const r = await fetch(CLAIM_ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
          body: JSON.stringify(payload),
        });
        if (!r.ok) throw new Error(`Server ${r.status}`);
      } else {
        // Fallback — open mailto with the details prefilled
        const lines = Object.entries(payload).map(([k,v]) => `${k}: ${v}`).join('\n');
        const subj = `Claim listing — ${winery.name}`;
        location.href = `mailto:${CLAIM_FALLBACK_EMAIL}?subject=${encodeURIComponent(subj)}&body=${encodeURIComponent(lines)}`;
      }
      setStep(3);
    } catch (err) {
      setError(`Could not submit: ${err.message}. Email ${CLAIM_FALLBACK_EMAIL} directly.`);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 200,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--paper)', padding: 40, maxWidth: 520, width: '100%',
        border: '1px solid var(--ink)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div className="kicker">Step {step} of 3 · Claim listing</div>
          <button onClick={onClose} style={{ background: 'transparent', border: 0, fontSize: 22, cursor: 'pointer', color: 'var(--ink-mute)' }}>×</button>
        </div>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, margin: '10px 0 4px', letterSpacing: '-0.015em' }}>
          {step === 1 && 'Verify ownership'}
          {step === 2 && 'Your details'}
          {step === 3 && 'Check your inbox'}
        </h3>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-mute)', margin: '0 0 22px' }}>
          {step === 1 && `How would you like to verify that you represent ${winery.name}?`}
          {step === 2 && 'Tell us who to contact about this claim.'}
          {step === 3 && 'We sent a verification link to the address you provided.'}
        </p>

        {step === 1 && (
          <div>
            {[
              { v: 'email', title: 'Winery-domain email', sub: `We'll send a link to someone@yourwinery.com` },
              { v: 'tabc', title: 'TABC permit number', sub: 'We match against the public Texas ABC record' },
              { v: 'callback', title: 'Phone callback', sub: 'We call the number on your winery website' },
            ].map(o => (
              <label key={o.v} style={{
                display: 'flex', gap: 14, padding: 16, border: '1px solid var(--rule)', marginBottom: 8,
                cursor: 'pointer', background: method === o.v ? 'var(--chip)' : 'var(--paper)',
              }}
                onClick={() => setMethod(o.v)}>
                <input type="radio" name="m" checked={method === o.v} readOnly />
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600 }}>{o.title}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-mute)', marginTop: 2 }}>{o.sub}</div>
                </div>
              </label>
            ))}
            <button className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 14 }} onClick={() => setStep(2)}>
              Continue
            </button>
          </div>
        )}

        {step === 2 && (
          <form onSubmit={submit}>
            <PortalField label="Your name" value={name} onChange={setName} required />
            <PortalField label="Role at winery" placeholder="Owner, winemaker, GM…" value={role} onChange={setRole} required />
            <PortalField
              label={method === 'email' ? 'Winery email' : method === 'tabc' ? 'TABC permit #' : 'Best phone number'}
              value={contact} onChange={setContact} required
              inputType={method === 'email' ? 'email' : method === 'callback' ? 'tel' : 'text'}
            />
            {error && (
              <div style={{
                padding: 12, background: 'rgba(122,26,26,0.08)',
                border: '1px solid var(--accent)', color: 'var(--accent)',
                fontSize: 13, marginBottom: 14, fontFamily: 'var(--font-body)',
              }}>{error}</div>
            )}
            <button className="btn" style={{ width: '100%', justifyContent: 'center', marginTop: 14 }}
              type="submit" disabled={submitting}>
              {submitting ? 'Submitting…' : 'Send verification'}
            </button>
          </form>
        )}

        {step === 3 && (
          <div>
            <div style={{ padding: 24, background: 'var(--chip)', marginBottom: 16, fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.55 }}>
              Click the link in the email to finish claiming your listing. Once verified, we'll show you the upgrade options and open the editor.
            </div>
            <button className="btn" style={{ width: '100%', justifyContent: 'center' }} onClick={onSubmit}>
              See plans →
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function PortalField({ label, placeholder, textarea, value, onChange, required, inputType = 'text' }) {
  const s = {
    width: '100%', padding: '10px 12px', fontSize: 14,
    border: '1px solid var(--rule)', borderRadius: 'var(--radius)',
    fontFamily: 'var(--font-ui)', background: 'var(--paper)', color: 'var(--ink)',
    marginTop: 4, marginBottom: 14,
  };
  const handle = (e) => onChange && onChange(e.target.value);
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>
        {label}{required && <span style={{ color: 'var(--accent)' }}> *</span>}
      </div>
      {textarea
        ? <textarea rows="4" placeholder={placeholder} style={s} value={value || ''} onChange={handle} required={required} />
        : <input type={inputType} placeholder={placeholder} style={s} value={value || ''} onChange={handle} required={required} />}
    </label>
  );
}

/* =================================================================
   PORTAL — the post-claim winery dashboard.
   Unchanged from previous version.
================================================================= */
function Portal({ onNav }) {
  const [tab, setTab] = React.useState('overview');
  return (
    <main style={{ background: 'var(--page-bg)', minHeight: '70vh' }}>
      <div style={{ borderBottom: '1px solid var(--rule)', background: 'var(--paper)' }}>
        <div className="container" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 32px' }}>
          <div>
            <div className="kicker">Winery Portal</div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 32, margin: '4px 0 0', letterSpacing: '-0.015em' }}>
              William Chris Vineyards
            </h1>
          </div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.08em' }}>
              VERIFIED · LAST EDITED 2 DAYS AGO
            </span>
            <button className="btn" onClick={() => onNav('winery')}>
              View public profile →
            </button>
          </div>
        </div>
        <div className="container" style={{ display: 'flex', gap: 28, padding: '0 32px' }}>
          {['overview', 'profile', 'bottles', 'events', 'reviews', 'analytics', 'billing'].map(t => (
            <button key={t} onClick={() => setTab(t)}
              style={{
                background: 'transparent', border: 0, padding: '14px 0',
                fontFamily: 'var(--font-ui)', fontSize: 13, fontWeight: 500,
                color: tab === t ? 'var(--ink)' : 'var(--ink-mute)', cursor: 'pointer',
                textTransform: 'capitalize',
                borderBottom: tab === t ? '2px solid var(--accent)' : '2px solid transparent',
                marginBottom: -1,
              }}>
              {t}
            </button>
          ))}
        </div>
      </div>

      <div className="container" style={{ padding: '40px 32px' }}>
        {tab === 'overview' && <PortalOverview onNav={onNav} />}
        {tab === 'profile' && <PortalProfile />}
        {tab === 'bottles' && <PortalBottles />}
        {tab === 'events' && <PortalEvents />}
        {tab === 'reviews' && <PortalReviews />}
        {tab === 'analytics' && <PortalAnalytics />}
        {tab === 'billing' && <PortalBilling onNav={onNav} />}
      </div>
    </main>
  );
}

function PortalOverview({ onNav }) {
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 32 }}>
        {[
          { k: '8,432', v: 'Profile views · 30d', d: '+12%' },
          { k: '342', v: 'Tasting clicks · 30d', d: '+8%' },
          { k: '4.8', v: 'Rating · 124 reviews', d: '+0.1' },
          { k: '3', v: 'New reviews · 7d', d: '' },
        ].map(s => (
          <div key={s.k} style={{ padding: 24, background: 'var(--paper)', border: '1px solid var(--rule)' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 700, letterSpacing: '-0.02em' }}>{s.k}</div>
            <div className="kicker" style={{ marginTop: 6 }}>{s.v}</div>
            {s.d && <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--accent-2)', marginTop: 8 }}>{s.d} vs prior</div>}
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 24 }}>
        <div style={{ padding: 28, background: 'var(--paper)', border: '1px solid var(--rule)' }}>
          <h3 className="h2" style={{ marginBottom: 16 }}>Action items</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              { p: 'high', t: 'Reply to 3 new reviews', n: 'Last review left 18 hrs ago.' },
              { p: 'med', t: 'Upload your 2024 vintage releases', n: 'Three bottles missing from the Cellar.' },
              { p: 'low', t: 'Refresh your tasting room photos', n: 'Current photos are 14 months old.' },
            ].map(a => (
              <div key={a.t} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 16, alignItems: 'center', padding: 16, background: 'var(--page-bg)', border: '1px solid var(--rule)' }}>
                <span style={{
                  width: 8, height: 8, borderRadius: '50%',
                  background: a.p === 'high' ? 'var(--accent)' : a.p === 'med' ? '#c89438' : 'var(--ink-mute)',
                }} />
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600 }}>{a.t}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-mute)', marginTop: 2 }}>{a.n}</div>
                </div>
                <button className="btn btn-ghost" style={{ padding: '6px 14px', fontSize: 11 }}>Resolve</button>
              </div>
            ))}
          </div>
        </div>

        <div style={{ padding: 28, background: 'var(--ink)', color: 'var(--paper)' }}>
          <div className="kicker" style={{ color: 'rgba(255,255,255,0.5)', marginBottom: 10 }}>Current plan</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 700 }}>Featured</div>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, opacity: 0.7, marginTop: 4 }}>$99 / month · next bill May 1</div>
          <button className="btn" onClick={() => onNav('plans')} style={{ width: '100%', justifyContent: 'center', marginTop: 18, background: 'var(--paper)', color: 'var(--ink)', borderColor: 'var(--paper)' }}>
            Upgrade to Premium
          </button>
        </div>
      </div>
    </div>
  );
}

function PortalProfile() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 32 }}>
      <div style={{ padding: 32, background: 'var(--paper)', border: '1px solid var(--rule)' }}>
        <h3 className="h2" style={{ marginBottom: 24 }}>Profile editor</h3>
        <PortalField label="Tagline" placeholder="100% Texas. 100% of the time." />
        <PortalField label="About" textarea />
        <PortalField label="Tasting room hours" />
        <PortalField label="Tasting experience" textarea />
        <button className="btn">Save changes</button>
      </div>
      <div>
        <div style={{ padding: 20, border: '1px solid var(--rule)', background: 'var(--paper)' }}>
          <div className="kicker" style={{ marginBottom: 10 }}>Live preview</div>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.5 }}>
            Changes save as a draft. Click "Publish" to make them live on your public profile.
          </div>
        </div>
      </div>
    </div>
  );
}

function PortalBottles() {
  const D = window.TX_DATA;
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
        <h3 className="h2">Bottles in the Cellar</h3>
        <button className="btn">+ Add bottle</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-body)', fontSize: 14 }}>
        <thead>
          <tr style={{ borderBottom: '2px solid var(--ink)' }}>
            {['Bottle', 'Vintage', 'Type', 'Price', 'Status', ''].map(h => (
              <th key={h} style={{ textAlign: 'left', padding: '12px 10px', fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-mute)' }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {D.bottles.slice(0, 4).map(b => (
            <tr key={b.id} style={{ borderBottom: '1px solid var(--rule)' }}>
              <td style={{ padding: '14px 10px', fontFamily: 'var(--font-display)', fontSize: 17 }}>{b.name}</td>
              <td style={{ padding: '14px 10px', color: 'var(--ink-soft)' }}>{b.vintage}</td>
              <td style={{ padding: '14px 10px', color: 'var(--ink-soft)' }}>{b.type}</td>
              <td style={{ padding: '14px 10px', color: 'var(--ink-soft)' }}>${b.price}</td>
              <td style={{ padding: '14px 10px' }}><span className="chip">Live</span></td>
              <td><button className="btn btn-ghost" style={{ padding: '4px 10px', fontSize: 10 }}>Edit</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function PortalEvents() {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
        <h3 className="h2">Upcoming events</h3>
        <button className="btn">+ Post event</button>
      </div>
      <div style={{ padding: 40, textAlign: 'center', background: 'var(--paper)', border: '1px dashed var(--rule)' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, color: 'var(--ink-soft)' }}>No events scheduled.</div>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-mute)', marginTop: 6 }}>
          Featured tier wineries can post up to 3 events per month. Premium gets unlimited.
        </p>
      </div>
    </div>
  );
}

function PortalReviews() {
  return (
    <div>
      <h3 className="h2" style={{ marginBottom: 18 }}>Recent reviews · respond as the winery</h3>
      {[
        { r: 5, who: 'Sarah J.', date: 'Apr 22', text: 'The Hye Mariage absolutely blew us away. The whole experience felt curated without being precious.' },
        { r: 4, who: 'Mike T.', date: 'Apr 19', text: 'Loved the wines, but the tasting room was packed on a Saturday at 2pm. Would book ahead next time.' },
        { r: 5, who: 'Elena R.', date: 'Apr 14', text: 'Easily the best Texas winery we visited on our trip. Chris was pouring himself and walked us through every wine.' },
      ].map((rv, i) => (
        <div key={i} style={{ padding: 24, background: 'var(--paper)', border: '1px solid var(--rule)', marginBottom: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600 }}>{rv.who}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-mute)' }}>★ {rv.r}.0 · {rv.date}</div>
            </div>
            <button className="btn btn-ghost" style={{ padding: '6px 14px', fontSize: 11 }}>Reply</button>
          </div>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-soft)', marginTop: 12 }}>{rv.text}</p>
        </div>
      ))}
    </div>
  );
}

function PortalAnalytics() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
      {[
        ['Profile views, 30d', '8,432'],
        ['Tasting clicks', '342'],
        ['Bottle clicks', '187'],
        ['Wine club signups', '24'],
        ['Avg. time on page', '2:14'],
        ['Top referrer', 'Google'],
      ].map(([k, v]) => (
        <div key={k} style={{ padding: 24, background: 'var(--paper)', border: '1px solid var(--rule)' }}>
          <div className="kicker" style={{ marginBottom: 8 }}>{k}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 700 }}>{v}</div>
        </div>
      ))}
    </div>
  );
}

function PortalBilling({ onNav }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 32 }}>
      <div style={{ padding: 32, background: 'var(--paper)', border: '1px solid var(--rule)' }}>
        <h3 className="h2" style={{ marginBottom: 24 }}>Billing</h3>
        <dl style={{ fontFamily: 'var(--font-body)', fontSize: 15, margin: 0 }}>
          {[
            ['Current plan', 'Featured · $99/mo'],
            ['Next bill', 'May 1, 2026'],
            ['Payment method', 'Visa ····4242'],
            ['Billing email', 'accounting@williamchris.com'],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '12px 0', borderBottom: '1px dotted var(--rule)' }}>
              <dt style={{ color: 'var(--ink-mute)' }}>{k}</dt>
              <dd style={{ margin: 0, color: 'var(--ink)', fontWeight: 500 }}>{v}</dd>
            </div>
          ))}
        </dl>
        <button className="btn" onClick={() => onNav('plans')} style={{ marginTop: 24 }}>
          Change plan
        </button>
      </div>
      <div style={{ padding: 24, background: 'var(--chip)' }}>
        <div className="kicker" style={{ marginBottom: 8 }}>Need help?</div>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--ink-soft)', margin: 0 }}>
          Questions about billing or your plan? Email <a style={{ color: 'var(--accent)' }}>billing@winesoftexas.com</a> — we answer within one business day.
        </p>
      </div>
    </div>
  );
}

function PortalSelect({ label, options }) {
  return (
    <label style={{ display: 'block', marginBottom: 14 }}>
      <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600, marginBottom: 4 }}>{label}</div>
      <select style={{ width: '100%', padding: '10px 12px', fontSize: 14, border: '1px solid var(--rule)', fontFamily: 'var(--font-ui)', background: 'var(--paper)' }}>
        {options.map(o => <option key={o}>{o}</option>)}
      </select>
    </label>
  );
}

window.ClaimPreview = ClaimPreview;
window.Portal = Portal;
