// site.jsx — ReturnScribe marketing landing (mono-trust layout × navy accent)

const { PhoneShell, ScreenReturnsDash, ScreenSubsList, ScreenReturnDetail, ScreenActivity } = window;

// Hardcoded production values (previously tweakable).
const ACCENT = '#1a3a52';
const HEADLINE = "What's still returnable. What's recurring.";
const PHONE_ARRANGEMENT = 'stacked';

// ── Wordmark glyph (abstract: a folded receipt + ring) ──────────
const WordmarkGlyph = ({ size = 22, accent = '#1a3a52' }) => (
  <svg width={size} height={size} viewBox="0 0 22 22" fill="none">
    <rect x="3" y="2" width="13" height="18" rx="1.6" stroke="#1a1a1a" strokeWidth="1.4" />
    <path d="M6 7.5h7M6 11h7M6 14.5h4" stroke="#1a1a1a" strokeWidth="1.2" strokeLinecap="round" />
    <circle cx="16" cy="16" r="4.2" fill={accent} stroke="#fafaf7" strokeWidth="1.4" />
    <path d="M14.5 16.2l1.1 1.1 2-2.2" stroke="#fafaf7" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
  </svg>
);

const Wordmark = ({ accent }) => (
  <a href="/" className="wordmark">
    <span className="wordmark-glyph"><WordmarkGlyph accent={accent} /></span>
    ReturnScribe
  </a>
);

// ── Nav ──────────────────────────────────────────────────────────
const Nav = ({ accent }) => {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-inner">
        <Wordmark accent={accent} />
        <div className="nav-links">
          <a href="#how">How it works</a>
          <a href="#privacy">Privacy</a>
          <a href="#faq">FAQ</a>
          <a className="nav-cta" href="#signup">Notify me</a>
        </div>
      </div>
    </nav>
  );
};

// ── Email signup ─────────────────────────────────────────────────
const EmailForm = () => {
  const [email, setEmail] = React.useState('');
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    setError('');
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) { setError('Please enter a valid email address.'); return; }
    // TODO: replace with Buttondown form action.
    // <form action="https://buttondown.com/api/emails/embed-subscribe/returnscribe" method="post">
    // For now, just show the success state.
    setSuccess(true);
  };

  if (success) {
    return (
      <div className="email-form" id="signup">
        <div className="email-success">
          <div className="email-success-mark">
            <svg width="11" height="11" viewBox="0 0 11 11" fill="none">
              <path d="M2 5.5L4.5 8L9 3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <div className="email-success-text">
            <strong>Thanks — we'll let you know when ReturnScribe launches.</strong>
            <span>Expected late June 2026. One email, no spam.</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <form className="email-form" id="signup" onSubmit={submit} noValidate>
      <div className="email-form-row">
        <input
          type="email"
          inputMode="email"
          autoComplete="email"
          placeholder="you@example.com"
          value={email}
          onChange={(e) => { setEmail(e.target.value); if (error) setError(''); }}
          aria-label="Email address"
        />
        <button type="submit">Notify me <span aria-hidden="true">→</span></button>
      </div>
      {error
        ? <div className="error">{error}</div>
        : <div className="email-form-foot">No spam. One email when we launch.</div>}
    </form>
  );
};

// ── Hero ─────────────────────────────────────────────────────────
const Hero = ({ accent, headline, phoneArrangement }) => {
  // Split headline at the period for italic styling on the second clause.
  const renderHeadline = () => {
    const parts = headline.split('.').map(s => s.trim()).filter(Boolean);
    if (parts.length >= 2) {
      return (
        <>
          {parts[0]}.<br />
          <em>{parts.slice(1).join('. ')}.</em>
        </>
      );
    }
    return headline;
  };

  return (
    <header className="hero">
      <div className="container">
        <div className="hero-grid">
          <div>
            <div className="hero-kicker">
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <span className="dot" /> 01 — Returns
              </span>
              <span>·</span>
              <span>02 — Subscriptions</span>
            </div>
            <h1 className="hero-title">{renderHeadline()}</h1>
            <p className="hero-sub">
              Connect your inbox. ReturnScribe finds your receipts, tracks return deadlines,
              and watches your subscriptions — all on your iPhone, with your data staying
              on your device.
            </p>
            <EmailForm />
            <div className="hero-meta">
              <span className="badge"><span className="dot" /> Coming soon to iPhone</span>
              <span>v1.0 · Late June 2026</span>
            </div>
            <div className="mockup-disclaimer">
              <span className="mockup-disclaimer-mark">◇</span>
              Phone mockups are conceptual previews — design in progress, not screenshots of a shipping app.
            </div>
          </div>
          <div role="img" aria-label="Conceptual mockups of the ReturnScribe iPhone app — pre-launch design previews, not screenshots of a shipping product.">
            <PhoneStack arrangement={phoneArrangement} accent={accent} />
          </div>
        </div>
      </div>
    </header>
  );
};

const PhoneStack = ({ arrangement, accent }) => {
  // Three arrangements; each shows two complementary screens.
  const isMobile = typeof window !== 'undefined' && window.matchMedia('(max-width: 880px)').matches;

  if (arrangement === 'single') {
    return (
      <div className="hero-phones">
        <div style={{ filter: 'drop-shadow(0 30px 50px rgba(0,0,0,0.16))' }}>
          <PhoneShell width={isMobile ? 280 : 320} accent={accent}>
            <ScreenReturnsDash accent={accent} />
          </PhoneShell>
        </div>
      </div>
    );
  }

  if (arrangement === 'side-by-side') {
    return (
      <div className="hero-phones" style={{ justifyContent: 'space-around' }}>
        <div style={{ filter: 'drop-shadow(0 24px 40px rgba(0,0,0,0.12))', marginTop: 24 }}>
          <PhoneShell width={isMobile ? 220 : 250} accent={accent}>
            <ScreenSubsList accent={accent} />
          </PhoneShell>
        </div>
        <div style={{ filter: 'drop-shadow(0 30px 50px rgba(0,0,0,0.18))' }}>
          <PhoneShell width={isMobile ? 240 : 270} accent={accent}>
            <ScreenReturnsDash accent={accent} />
          </PhoneShell>
        </div>
      </div>
    );
  }

  // Default: stacked / overlapping (mono-trust look)
  return (
    <div className="hero-phones">
      <div style={{
        position: 'absolute', right: isMobile ? '52%' : 160, top: 30,
        transform: 'rotate(-4deg)',
        filter: 'drop-shadow(0 30px 50px rgba(0,0,0,0.10))',
      }}>
        <PhoneShell width={isMobile ? 200 : 240} accent={accent}>
          <ScreenSubsList accent={accent} />
        </PhoneShell>
      </div>
      <div style={{
        position: 'absolute', right: isMobile ? '-2%' : 0, top: 90,
        transform: 'rotate(3deg)',
        filter: 'drop-shadow(0 30px 50px rgba(0,0,0,0.18))',
      }}>
        <PhoneShell width={isMobile ? 220 : 270} accent={accent}>
          <ScreenReturnsDash accent={accent} />
        </PhoneShell>
      </div>
    </div>
  );
};

// ── How it works ─────────────────────────────────────────────────
const HowItWorks = () => (
  <section className="section" id="how">
    <div className="container">
      <div className="section-head">
        <div className="kicker">How it works</div>
        <div>
          <h2 className="section-title">
            Three steps. <em>Then it runs in the background.</em>
          </h2>
        </div>
      </div>
      <div className="steps">
        <Step n="01" title="Connect Gmail or Outlook">
          Read-only OAuth — we never see your password, and your inbox stays in your inbox.
          Revoke access anytime from your provider's dashboard or the app.
        </Step>
        <Step n="02" title="We find your purchases automatically">
          ReturnScribe scans only purchase confirmations and subscription receipts, on your
          iPhone. Raw email content is never stored or transmitted.
        </Step>
        <Step n="03" title="Get reminded before it's too late">
          Push notifications before return windows close, before subscriptions renew, and
          before free trials become paid. Snooze, swipe, done.
        </Step>
      </div>
    </div>
  </section>
);

const Step = ({ n, title, children }) => (
  <div className="step">
    <div className="step-num">{n}</div>
    <h3 className="step-title">{title}</h3>
    <p className="step-body">{children}</p>
  </div>
);

// ── Features ─────────────────────────────────────────────────────
const Check = () => (
  <svg className="check" width="18" height="18" viewBox="0 0 18 18" fill="none">
    <circle cx="9" cy="9" r="8.25" stroke="currentColor" strokeWidth="1" opacity="0.35" />
    <path d="M5.5 9.2L8 11.7L12.8 6.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

const FeatureItem = ({ name, desc }) => (
  <li>
    <Check />
    <div>
      <span className="name">{name}</span>
      <span className="desc">{desc}</span>
    </div>
  </li>
);

const Features = () => (
  <section className="section" id="features">
    <div className="container">
      <div className="section-head">
        <div className="kicker">What it does</div>
        <div>
          <h2 className="section-title">
            Two purchase events that actually matter — <em>handled equally well</em>.
          </h2>
          <p className="section-lead">
            ReturnScribe doesn't try to be a budgeting app, an inbox cleaner, or an AI
            assistant. It does two things, properly.
          </p>
        </div>
      </div>
      <div className="features">
        <div className="feature-col">
          <div className="feature-head">
            <h3 className="feature-title">Returns</h3>
            <div className="feature-tag">01</div>
          </div>
          <ul className="feature-list">
            <FeatureItem name="Automatic receipt detection" desc="Purchases from major retailers parsed straight from order-confirmation emails." />
            <FeatureItem name="Return-window countdown" desc="Each item shows the days remaining against the retailer's published policy." />
            <FeatureItem name="Closing-soon alerts" desc="Push notifications a few days before each return window expires." />
            <FeatureItem name="Organized by store" desc="Group items together so you can run a single return trip per retailer." />
            <FeatureItem name="Refund tracking" desc="Mark items as returned and watch refund confirmations land." />
          </ul>
        </div>
        <div className="feature-col">
          <div className="feature-head">
            <h3 className="feature-title">Subscriptions</h3>
            <div className="feature-tag">02</div>
          </div>
          <ul className="feature-list">
            <FeatureItem name="Auto-detect recurring charges" desc="Recurring receipts surface as subscriptions you can review and confirm." />
            <FeatureItem name="Renewal reminders" desc="Heads-up notifications before each renewal so a charge is never a surprise." />
            <FeatureItem name="Monthly cost breakdown" desc="See your real monthly subscription spend at a glance." />
            <FeatureItem name="Cancellation tracking" desc="Mark a sub as cancelled and we'll watch for the confirmation receipt." />
            <FeatureItem name="Trial-to-paid warnings" desc="Get warned before a free trial silently converts into a recurring charge." />
          </ul>
        </div>
      </div>
    </div>
  </section>
);

// ── Privacy ──────────────────────────────────────────────────────
const Privacy = () => (
  <section className="section" id="privacy">
    <div className="container">
      <div className="section-head">
        <div className="kicker">Privacy is the product</div>
        <div>
          <h2 className="section-title">
            Built on the assumption that <em>your inbox is yours</em>.
          </h2>
          <p className="section-lead">
            ReturnScribe is a native iOS app that processes your email locally. The
            architecture is the privacy story — there's nothing for us to leak, because
            there's nothing for us to hold.
          </p>
        </div>
      </div>
      <div className="privacy-grid">
        <PrivacyItem title="Native iOS — not a web wrapper">
          Built in SwiftUI for iOS 17+. Your data lives in encrypted on-device storage
          (NSFileProtectionComplete) — not in a server-side mailbox cache.
        </PrivacyItem>
        <PrivacyItem title="Read-only email access">
          OAuth scopes are limited to read-only Gmail / Microsoft Graph. We can't send,
          delete, or modify anything in your inbox.
        </PrivacyItem>
        <PrivacyItem title="Raw email bodies are never persisted">
          A 256 KB body cap is applied before parsing, structured purchase data is
          extracted, and the raw text is dropped — compile-enforced in the codebase.
        </PrivacyItem>
        <PrivacyItem title="No advertising, no third-party tracking">
          No analytics SDKs, no ad networks, no behavioural profiling. Required-Reason
          API usage is declared in the App Store privacy manifest.
        </PrivacyItem>
        <PrivacyItem title="OAuth tokens stay in the Keychain">
          Refresh tokens are stored with <code style={{ fontFamily: 'JetBrains Mono', fontSize: 13 }}>kSecAttrAccessibleWhenUnlockedThisDeviceOnly</code> — they don't sync to iCloud.
        </PrivacyItem>
        <PrivacyItem title="Open about what we do">
          Read the full details in the <a href="privacy.html">privacy policy</a>. If
          something there is unclear, write to <a href="mailto:privacy@returnscribe.com">privacy@returnscribe.com</a>.
        </PrivacyItem>
      </div>
    </div>
  </section>
);

const PrivacyItem = ({ title, children }) => (
  <div className="privacy-item">
    <h3 className="privacy-title">{title}</h3>
    <p className="privacy-body">{children}</p>
  </div>
);

// ── FAQ ──────────────────────────────────────────────────────────
const FAQ_ITEMS = [
  { q: 'Is my email data safe?', a: "Yes. ReturnScribe uses read-only OAuth — we cannot send, delete, or modify anything. Email scanning happens on your iPhone, not on a server. Raw email bodies are never stored or transmitted; only structured purchase data (merchant, amount, date, return window) is kept, and that's stored in encrypted on-device storage." },
  { q: 'What email providers are supported?', a: 'Gmail and Outlook (Microsoft Graph) at launch. iCloud Mail and Yahoo Mail are planned for a future release. Multiple accounts on the same provider are supported.' },
  { q: 'How much does it cost?', a: "Free to install with a 10-day free trial. After the trial, premium features are $4.99/month — managed through your Apple ID. We'll share more details closer to launch." },
  { q: 'When does it launch?', a: 'Late June 2026. Sign up above and you\'ll get one email when it goes live on the App Store.' },
  { q: 'How is this different from other apps?', a: "ReturnScribe is a native iOS app built privacy-first from the ground up — not a web shell, not an AI chatbot, not a budgeting suite. It focuses on the two purchase events that actually have time-sensitive consequences (returns closing, subscriptions renewing) and does them properly." },
];

const FAQ = () => {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="section" id="faq">
      <div className="container">
        <div className="section-head">
          <div className="kicker">Questions</div>
          <div>
            <h2 className="section-title">Things people <em>ask first</em>.</h2>
          </div>
        </div>
        <div className="faq">
          {FAQ_ITEMS.map((it, i) => (
            <div className={`faq-item ${open === i ? 'open' : ''}`} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{it.q}</span>
                <span className="faq-mark">+</span>
              </button>
              <div className="faq-a">{it.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ── Footer ───────────────────────────────────────────────────────
const Footer = ({ accent }) => (
  <footer className="footer">
    <div className="container">
      <div className="footer-grid">
        <div>
          <Wordmark accent={accent} />
          <p className="footer-blurb">
            A privacy-first iPhone app for tracking what you've purchased — what's still
            returnable, and what's recurring. Built by an indie developer in Virginia.
          </p>
        </div>
        <div>
          <h4>Product</h4>
          <ul>
            <li><a href="#how">How it works</a></li>
            <li><a href="#features">Features</a></li>
            <li><a href="#privacy">Privacy</a></li>
            <li><a href="#faq">FAQ</a></li>
          </ul>
        </div>
        <div>
          <h4>Legal &amp; contact</h4>
          <ul>
            <li><a href="privacy.html">Privacy policy</a></li>
            <li><a href="terms.html">Terms of use</a></li>
            <li><a href="mailto:info@returnscribe.com">info@returnscribe.com</a></li>
            <li><a href="mailto:privacy@returnscribe.com">privacy@returnscribe.com</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 ReturnScribe. All rights reserved.</span>
        <span>v1.0 · returnscribe.com</span>
      </div>
    </div>
  </footer>
);

// ── App ──────────────────────────────────────────────────────────
const App = () => (
  <>
    <Nav accent={ACCENT} />
    <main>
      <Hero accent={ACCENT} headline={HEADLINE} phoneArrangement={PHONE_ARRANGEMENT} />
      <HowItWorks />
      <Features />
      <Privacy />
      <FAQ />
    </main>
    <Footer accent={ACCENT} />
  </>
);

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