/* PillarBlock — Landing page
   Single-file React component. Tweakable via the Tweaks panel.
   Brand-pack assets: brand/PillarBlock/png/pb_Logo_tight.png */

const { useState, useMemo } = React;

// ── Official PillarBlock symbol — vector geometry from brand pack
const Symbol = ({ size = 24, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 283.5 283.5" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
    <polygon fill={color} points="133.5,166.1 133.5,117.4 125.4,109.3 76.8,109.3 68.6,117.4 68.6,206.6 101.1,174.2 125.4,174.2"/>
    <polygon fill={color} points="214.8,117.4 214.8,166.1 206.7,174.2 158,174.2 149.9,166.1 149.9,76.8 182.4,109.3 206.7,109.3"/>
  </svg>
);

// Tiny check icon
const Check = ({ size = 16 }) => (
  <svg className="check" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="m5 12 5 5L20 7"/>
  </svg>
);

const ArrowRight = ({ size = 16 }) => (
  <svg className="arrow" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>
  </svg>
);

// Feature icons — geometric, no emoji, drawn to match the chunky bevel of the mark
const PayIcon = () => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="2" y="6" width="20" height="14" rx="2"/>
    <path d="M2 11h20"/>
    <path d="M6 16h4"/>
  </svg>
);
const ShieldIcon = () => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
    <path d="m9 12 2 2 4-4"/>
  </svg>
);
const BookIcon = () => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20V3H6.5A2.5 2.5 0 0 0 4 5.5z"/>
    <path d="M4 19.5A2.5 2.5 0 0 0 6.5 22H20v-5"/>
    <path d="M9 7h7"/><path d="M9 11h7"/>
  </svg>
);

// Float chip icons
const ZapIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M13 2 4 14h7l-1 8 9-12h-7l1-8z"/>
  </svg>
);
const GlobeIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <circle cx="12" cy="12" r="10"/>
    <path d="M2 12h20"/><path d="M12 2a15 15 0 0 1 0 20"/><path d="M12 2a15 15 0 0 0 0 20"/>
  </svg>
);
const FlowArrow = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>
  </svg>
);
const XIcon = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
  </svg>
);
const MailIcon = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <rect x="2" y="4" width="20" height="16" rx="2"/>
    <path d="m2 7 10 6 10-6"/>
  </svg>
);

// ── DEFAULT TWEAK VALUES ──────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headline": "Finance control without finance bottlenecks.",
  "headlineAccent": "without finance bottlenecks",
  "subhead": "The CFO operating system for complex B2B operations — settling on Solana, reconciling to your ERP.",
  "ctaMode": "capture",
  "ctaLabel": "Get early access",
  "ctaEmail": "hello@pillarblock.com",
  "ctaUrl": "",
  "showFloatChips": true,
  "showTrustBar": true,
  "showBottomCTA": true
}/*EDITMODE-END*/;

// ── HEADLINE (with accented span) ─────────────────────────────────
function Headline({ text, accent }) {
  if (!accent || !text.includes(accent)) {
    return <h1 className="hero-headline">{text}</h1>;
  }
  const idx = text.indexOf(accent);
  const before = text.slice(0, idx);
  const after = text.slice(idx + accent.length);
  return (
    <h1 className="hero-headline">
      {before}<em>{accent}</em>{after}
    </h1>
  );
}

// ── CAPTURE BACKEND ──────────────────────────────────────────────
// Posts to the early-access-capture Supabase edge function. The anon key
// is safe to expose publicly (designed for client use); the actual write
// is gated server-side by the edge fn's email validation + service-role
// access to the early_access_signups table.
const CAPTURE_ENDPOINT = 'https://yonukafjydynqfokztch.supabase.co/functions/v1/early-access-capture';
const CAPTURE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlvbnVrYWZqeWR5bnFmb2t6dGNoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzU4NDM2MzEsImV4cCI6MjA5MTQxOTYzMX0.5GC23xmpcn8Sq-Ay-sybwbW-AukieqngUTJZJ2x4wak';

// ── CTA ───────────────────────────────────────────────────────────
function CTA({ mode, label, email, url, where = 'hero' }) {
  const [submittedEmail, setSubmittedEmail] = useState('');
  const [inputEmail, setInputEmail] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');

  if (mode === 'capture') {
    if (submittedEmail) {
      return (
        <div className="capture-thanks">
          <Check size={16}/>
          Thanks — we'll reach out at <strong style={{marginLeft:4, color:'var(--navy)'}}>{submittedEmail}</strong>
        </div>
      );
    }
    return (
      <>
        <form className="capture" onSubmit={async (e) => {
          e.preventDefault();
          const email = inputEmail.trim();
          if (!email || !/\S+@\S+\.\S+/.test(email)) {
            setSubmitError('Please enter a valid email address.');
            return;
          }
          setSubmitting(true);
          setSubmitError('');
          try {
            const res = await fetch(CAPTURE_ENDPOINT, {
              method: 'POST',
              headers: {
                'apikey': CAPTURE_ANON_KEY,
                'Authorization': `Bearer ${CAPTURE_ANON_KEY}`,
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ email, source: `landing_${where}` }),
            });
            const data = await res.json().catch(() => ({}));
            if (!res.ok) {
              setSubmitError(data?.error || 'Could not save your request. Please try again.');
              return;
            }
            setSubmittedEmail(email);
          } catch (err) {
            setSubmitError('Network error. Please check your connection and try again.');
          } finally {
            setSubmitting(false);
          }
        }}>
          <input
            type="email"
            placeholder="you@company.com"
            value={inputEmail}
            onChange={(e) => { setInputEmail(e.target.value); if (submitError) setSubmitError(''); }}
            required
            disabled={submitting}
            aria-label="Work email"
          />
          <button type="submit" disabled={submitting}>
            {submitting ? 'Submitting…' : <>{label} <ArrowRight size={14}/></>}
          </button>
        </form>
        {submitError && (
          <div className="capture-note" style={{color:'#c43d3d'}}>{submitError}</div>
        )}
        {!submitError && where === 'hero' && (
          <div className="capture-note">No spam. Early access invites only.</div>
        )}
      </>
    );
  }

  // mailto / url modes
  const href = mode === 'url' && url ? url : `mailto:${email}?subject=${encodeURIComponent('PillarBlock — Early access')}`;
  return (
    <div className="cta-row">
      <a className="btn btn-primary" href={href}>
        {label} <ArrowRight/>
      </a>
      {where === 'hero' && (
        <a className="btn btn-ghost" href="#features">See how it works →</a>
      )}
    </div>
  );
}

// ── PAYMENT CARD VISUAL ───────────────────────────────────────────
function PaymentCard() {
  return (
    <div className="payment-card">
      <div className="pc-head">
        <div className="pc-mark">
          <img src="brand/PillarBlock/png/pb_Logo_tight.png" alt="" aria-hidden="true" style={{height:27, width:'auto', display:'block', filter:'brightness(0) invert(1)'}}/>
        </div>
        <span className="pc-status"><span className="dot"/> Sending</span>
      </div>
      <div className="pc-amount">
        <span className="currency">USDC</span>48,250.00
      </div>
      <div className="pc-label">Vendor payout · Invoice #2026-0418</div>

      <div className="pc-flow">
        <div className="pc-party">
          <div className="pc-party-name">Your Treasury</div>
          <div className="pc-party-meta">Treasury · Multi-sig</div>
        </div>
        <div className="pc-arrow"><FlowArrow/></div>
        <div className="pc-party" style={{textAlign:'right'}}>
          <div className="pc-party-name">Vendor (DE)</div>
          <div className="pc-party-meta">DE89…3000</div>
        </div>
      </div>
      <div className="pc-rail">
        <span className="rail-dot"/>
        <span>Solana · USDC</span>
        <span className="rail-time">~3s</span>
      </div>
    </div>
  );
}

// ── APP ───────────────────────────────────────────────────────────
function App() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  return (
    <>
      {/* Top nav */}
      <nav className="nav">
        <div className="nav-inner">
          <a className="nav-logo" href="#" aria-label="PillarBlock home">
            <img src="brand/PillarBlock/png/pb_Logo_tight.png" alt="PillarBlock" style={{height:50, width:'auto', display:'block'}}/>
          </a>
          <span className="nav-spacer"/>
          <a className="nav-link" href="#features">Product</a>
          <a className="nav-link" href="#features">Security</a>
          <a className="nav-link" href={`mailto:${tweaks.ctaEmail}`}>Contact</a>
          <a className="nav-cta" href={tweaks.ctaMode === 'url' && tweaks.ctaUrl ? tweaks.ctaUrl : `mailto:${tweaks.ctaEmail}`}>
            {tweaks.ctaLabel}
          </a>
        </div>
      </nav>

      {/* Hero */}
      <header className="hero">
        <div className="hero-inner">
          <div>
            <span className="hero-eyebrow"><span className="pulse"/> Now in private beta</span>
            <Headline text={tweaks.headline} accent={tweaks.headlineAccent}/>
            <p className="hero-sub">{tweaks.subhead}</p>
            <CTA
              mode={tweaks.ctaMode}
              label={tweaks.ctaLabel}
              email={tweaks.ctaEmail}
              url={tweaks.ctaUrl}
              where="hero"
            />
          </div>
          <div className="hero-visual" aria-hidden="true">
            <PaymentCard/>
            {tweaks.showFloatChips && (
              <>
                <div className="float-chip float-chip-1">
                  <div className="fc-icon"><ZapIcon/></div>
                  <div>
                    <div className="fc-label">On-chain settlement</div>
                    <div className="fc-value">~3 seconds</div>
                  </div>
                </div>
                <div className="float-chip float-chip-2">
                  <div className="fc-icon"><GlobeIcon/></div>
                  <div>
                    <div className="fc-label">Coverage</div>
                    <div className="fc-value">160+ countries</div>
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      </header>

      {/* Trust bar */}
      {tweaks.showTrustBar && (
        <section className="trust">
          <div className="trust-inner">
            <span className="trust-label">Built for finance teams</span>
            <div className="trust-items">
              <div className="trust-item"><Check/> SOC 2-aligned controls</div>
              <div className="trust-item"><Check/> Regulated USDC partner</div>
              <div className="trust-item"><Check/> Multi-tier approvals</div>
              <div className="trust-item"><Check/> Full audit trail</div>
            </div>
          </div>
        </section>
      )}

      {/* Features */}
      <section className="features" id="features">
        <div className="features-head">
          <div className="features-eyebrow">What you get</div>
          <h2 className="features-title">
            Everything finance needs to send money — without the wait, the spreadsheet, or the wire fees.
          </h2>
        </div>
        <div className="features-grid">
          <article className="feature">
            <div className="feature-icon"><PayIcon/></div>
            <h3 className="feature-title">Pay any vendor, anywhere</h3>
            <p className="feature-body">
              Global USDC payouts with all-in cost shown upfront — no hidden FX, no correspondent fees, no "your wire is being investigated" emails.
            </p>
            <div className="feature-tags">
              <span className="feature-tag">USDC</span>
              <span className="feature-tag">160+ countries</span>
              <span className="feature-tag">Upfront pricing</span>
            </div>
          </article>

          <article className="feature">
            <div className="feature-icon"><ShieldIcon/></div>
            <h3 className="feature-title">Approval workflows that match your team</h3>
            <p className="feature-body">
              Multi-tier approvals, role-based limits, and full audit trail. Built-in BEC defense — every payment is verified against your vendor record before it leaves.
            </p>
            <div className="feature-tags">
              <span className="feature-tag">Multi-tier</span>
              <span className="feature-tag">Audit trail</span>
              <span className="feature-tag">BEC defense</span>
            </div>
          </article>

          <article className="feature">
            <div className="feature-icon"><BookIcon/></div>
            <h3 className="feature-title">Reconciles to your books</h3>
            <p className="feature-body">
              Built to write back into QuickBooks and Xero — so finance closes without re-keying every payment.
            </p>
            <div className="feature-tags">
              <span className="feature-tag">QuickBooks</span>
              <span className="feature-tag">Xero</span>
              <span className="feature-tag">Auto-coded</span>
            </div>
          </article>
        </div>
      </section>

      {/* Bottom CTA */}
      {tweaks.showBottomCTA && (
        <section className="bottom-cta">
          <div className="bottom-cta-inner">
            <h2>Move money the way your team already works.</h2>
            <p>Private beta is open to a small group of finance teams. Tell us about your operation — we'll be in touch within two business days.</p>
            <CTA
              mode={tweaks.ctaMode}
              label={tweaks.ctaLabel}
              email={tweaks.ctaEmail}
              url={tweaks.ctaUrl}
              where="bottom"
            />
          </div>
          <div className="bottom-cta-mark">
            <Symbol size={280} color="rgba(255,255,255,0.06)"/>
          </div>
        </section>
      )}

      {/* Footer */}
      <footer className="footer">
        <div className="footer-inner">
          <div className="footer-brand">
            <img src="brand/PillarBlock/png/pb_Logo_tight.png" alt="PillarBlock" style={{height:56, width:'auto', display:'block', marginBottom:24}}/>
            <p className="footer-tag">The CFO operating system for complex B2B operations — settling on Solana.</p>
          </div>
          <div>
            <h4 className="footer-col-title">Connect</h4>
            <div className="footer-col">
              <a href={`mailto:${tweaks.ctaEmail}`}><MailIcon/> {tweaks.ctaEmail}</a>
              <a href="https://x.com/pillarblock_" target="_blank" rel="noopener noreferrer"><XIcon/> @pillarblock_</a>
            </div>
          </div>
          <div>
            <h4 className="footer-col-title">Company</h4>
            <div className="footer-col">
              <a href="#features">Product</a>
            </div>
          </div>
          <div>
            <h4 className="footer-col-title">Legal</h4>
            <div className="footer-col">
              <a href="terms.html">Terms of Service</a>
              <a href="privacy.html">Privacy Policy</a>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 PillarBlock. All rights reserved.</span>
          <span className="built">Built on Solana · Powered by USDC</span>
        </div>
      </footer>

      {/* ── Tweaks panel ── */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Headline">
          <window.TweakText
            label="Headline"
            value={tweaks.headline}
            onChange={(v) => setTweak('headline', v)}
            multiline
          />
          <window.TweakText
            label="Accent (sub-string of headline rendered in blue)"
            value={tweaks.headlineAccent}
            onChange={(v) => setTweak('headlineAccent', v)}
          />
          <window.TweakText
            label="Subhead"
            value={tweaks.subhead}
            onChange={(v) => setTweak('subhead', v)}
            multiline
          />
        </window.TweakSection>

        <window.TweakSection title="Call to action">
          <window.TweakRadio
            label="CTA mode"
            options={[
              { label: 'Email link', value: 'mailto' },
              { label: 'Inline capture', value: 'capture' },
              { label: 'External URL', value: 'url' },
            ]}
            value={tweaks.ctaMode}
            onChange={(v) => setTweak('ctaMode', v)}
          />
          <window.TweakText
            label="Button label"
            value={tweaks.ctaLabel}
            onChange={(v) => setTweak('ctaLabel', v)}
          />
          <window.TweakText
            label="Contact email"
            value={tweaks.ctaEmail}
            onChange={(v) => setTweak('ctaEmail', v)}
          />
          {tweaks.ctaMode === 'url' && (
            <window.TweakText
              label="External URL (Tally/Typeform)"
              value={tweaks.ctaUrl}
              onChange={(v) => setTweak('ctaUrl', v)}
            />
          )}
        </window.TweakSection>

        <window.TweakSection title="Layout">
          <window.TweakToggle
            label="Floating callout chips"
            value={tweaks.showFloatChips}
            onChange={(v) => setTweak('showFloatChips', v)}
          />
          <window.TweakToggle
            label="Trust bar"
            value={tweaks.showTrustBar}
            onChange={(v) => setTweak('showTrustBar', v)}
          />
          <window.TweakToggle
            label="Bottom CTA banner"
            value={tweaks.showBottomCTA}
            onChange={(v) => setTweak('showBottomCTA', v)}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
