/* eslint-disable */
function HomePage({ onNav }) {
  return (
    <>
      <Hero
        title="Custom CRE tools, built by the practitioners who use them."
        body="We model deals before our clients sign them — and audit the ones they've already signed. AI and modern tooling, implemented to maximize returns at every stage of a commercial Real Estate asset."
        cta="Request a Model"
        onCta={() => onNav('contact')}
      />
      <section className="ccg-section">
        <SectionHeader kicker="What we do" title="Three practice areas." />
        <div className="ccg-tile-grid">
          <ServiceTile
            icon="bar-chart-3"
            title="Investment Analysis"
            body="Custom financial models, proforma audits, and sale-vs-hold analyses tailored to each client's deal."
          />
          <ServiceTile
            icon="cpu"
            title="AI Implementation"
            body="AI implementation across all aspects of commercial real estate — due diligence, property management, marketing, and disposition."
          />
          <ServiceTile
            icon="building-2"
            title="Development Services"
            body="Strategy, entitlement, and financial structuring for ground-up and redevelopment projects."
          />
        </div>
      </section>
      <section className="ccg-section ccg-section--alt">
        <Callout>
          <strong>Our key objective</strong> is always to build highly functional and automated models that may be controlled from a clearly defined set of input assumptions.
        </Callout>
      </section>
    </>
  );
}
window.HomePage = HomePage;

/* ---------- Contact: split panel, dark left ---------- */
function ContactPage() {
  const [sent, setSent] = React.useState(false);
  return (
    <section className="ccg-contact-c">
      <div className="ccg-contact-c__inner">
        <aside className="ccg-contact-c__left">
          <div className="ccg-eyebrow ccg-contact-c__eyebrow">Contact</div>
          <h2 className="ccg-contact-c__title">Tell us about your project.</h2>
          <hr className="ccg-contact-c__rule" />
          <p className="ccg-contact-c__lede">
            Every partnership begins with a short conversation about the deal, the assumptions, and what questions you are hoping to answer.
          </p>
          <dl className="ccg-contact-c__defs">
            <dt>Direct</dt>
            <dd>info@CarpenterConsultingGroup.com<br/>303.570.5171</dd>
            <dt>Office</dt>
            <dd>Denver, CO &mdash; by appointment</dd>
            <dt>What to expect</dt>
            <dd>First reply within one business day. NDA on request.</dd>
          </dl>
        </aside>
        <div className="ccg-contact-c__right">
          <ContactForm sent={sent} onSubmit={() => setSent(true)} />
        </div>
      </div>
    </section>
  );
}
window.ContactPage = ContactPage;

function LoginPage({ onNav }) {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [remember, setRemember] = React.useState(true);
  const [error, setError] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [resetSent, setResetSent] = React.useState(false);

  async function submit(e) {
    e.preventDefault();
    if (!email || !password) { setError('Email and password are required.'); return; }
    if (!window.supabaseClient) { setError('Auth service unavailable. Please refresh.'); return; }
    setError(''); setBusy(true);
    const { error: authError } = await window.supabaseClient.auth.signInWithPassword({ email, password });
    setBusy(false);
    if (authError) setError(authError.message);
  }

  async function forgotPassword(e) {
    e.preventDefault();
    if (!email) { setError('Enter your email above first, then click Forgot password.'); return; }
    if (!window.supabaseClient) { setError('Auth service unavailable. Please refresh.'); return; }
    setError(''); setBusy(true);
    const { error: resetError } = await window.supabaseClient.auth.resetPasswordForEmail(email, {
      redirectTo: window.location.origin + '/'
    });
    setBusy(false);
    if (resetError) setError(resetError.message); else setResetSent(true);
  }

  return (
    <section className="ccg-section ccg-login">
      <div className="ccg-login__card">
        <h2 className="ccg-login__title">Partner Login</h2>
        <hr className="ccg-rule-accent" />
        <p className="ccg-login__lede">
          Secure access to your custom tools, data, and shared workspaces.
        </p>

        <form className="ccg-login__form" onSubmit={submit}>
          <div className="ccg-field">
            <label className="ccg-label" htmlFor="login-email">Email</label>
            <input id="login-email" className="ccg-input" type="email" autoComplete="email"
              value={email} onChange={(e) => setEmail(e.target.value)} required disabled={busy} />
          </div>
          <div className="ccg-field">
            <label className="ccg-label" htmlFor="login-pw">Password</label>
            <input id="login-pw" className="ccg-input" type="password" autoComplete="current-password"
              value={password} onChange={(e) => setPassword(e.target.value)} required disabled={busy} />
          </div>

          <div className="ccg-login__row">
            <label className="ccg-login__remember">
              <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
              <span>Remember me on this device</span>
            </label>
            <a className="ccg-login__forgot" href="#" onClick={forgotPassword}>Forgot password?</a>
          </div>

          {error ? <div className="ccg-login__error">{error}</div> : null}
          {resetSent ? <div className="ccg-login__notice">Password reset email sent. Check your inbox.</div> : null}

          <button type="submit" className="ccg-btn ccg-btn--primary ccg-login__submit" disabled={busy}>
            {busy ? 'Signing in…' : 'Sign In'}
          </button>
        </form>

        <hr className="ccg-rule-full" />
        <p className="ccg-login__foot">
          Not a partner yet? <a href="#contact" onClick={(e) => { e.preventDefault(); onNav('contact'); }}>Contact us</a> to start an engagement.
        </p>
      </div>
    </section>
  );
}
window.LoginPage = LoginPage;

function PortalPage({ session, partner, onSignOut }) {
  const [deals, setDeals] = React.useState([]);
  const [docs, setDocs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!session || !window.supabaseClient) return;
    (async () => {
      const sb = window.supabaseClient;
      const [{ data: d }, { data: docs }] = await Promise.all([
        sb.from('deals').select('*').eq('partner_id', session.user.id).order('updated_at', { ascending: false }),
        sb.from('documents').select('*').eq('partner_id', session.user.id).order('created_at', { ascending: false }),
      ]);
      setDeals(d || []);
      setDocs(docs || []);
      setLoading(false);
    })();
  }, [session && session.user.id]);

  if (loading) {
    return (
      <section className="ccg-section ccg-login">
        <div className="ccg-login__card">Loading…</div>
      </section>
    );
  }

  const displayName = (partner && partner.full_name) || session.user.email;

  return (
    <section className="ccg-section ccg-portal">
      <div className="ccg-portal__head">
        <div>
          <div className="ccg-eyebrow">Partner Portal</div>
          <h2 className="ccg-portal__title">Welcome, {displayName}.</h2>
          <hr className="ccg-rule-accent" />
        </div>
        <button className="ccg-btn ccg-btn--ghost" onClick={onSignOut}>Sign Out</button>
      </div>

      <div className="ccg-portal__grid">
        <div className="ccg-portal__card">
          <div className="ccg-eyebrow">Profile</div>
          <dl className="ccg-portal__defs">
            <dt>Email</dt><dd>{session.user.email}</dd>
            <dt>Company</dt><dd>{(partner && partner.company) || <span className="ccg-portal__muted">Not set</span>}</dd>
            <dt>Phone</dt><dd>{(partner && partner.phone) || <span className="ccg-portal__muted">Not set</span>}</dd>
          </dl>
        </div>

        <div className="ccg-portal__card">
          <div className="ccg-portal__cardhead">
            <div className="ccg-eyebrow">Projects</div>
            <span className="ccg-portal__count">{deals.length + 2}</span>
          </div>
          {/* SkillCourt — static project folder */}
          <div className="ccg-portal__project">
            <div className="ccg-portal__project-header">
              <i data-lucide="folder" className="ccg-portal__project-icon"></i>
              <strong>SkillCourt</strong>
            </div>
            <ul className="ccg-portal__list ccg-portal__list--files">
              <li>
                <a href="portal/skillcourt-report.html" target="_blank" rel="noopener noreferrer" className="ccg-portal__file-link">
                  <i data-lucide="file-text" className="ccg-portal__file-icon"></i>
                  Report
                </a>
              </li>
              <li>
                <a href="portal/skillcourt-battlecard.html" target="_blank" rel="noopener noreferrer" className="ccg-portal__file-link">
                  <i data-lucide="layout-dashboard" className="ccg-portal__file-icon"></i>
                  Battlecard
                </a>
              </li>
            </ul>
          </div>
          {/* Colorado Auction Tracking — static project folder */}
          <div className="ccg-portal__project">
            <div className="ccg-portal__project-header">
              <i data-lucide="folder" className="ccg-portal__project-icon"></i>
              <strong>Colorado Auction Tracking</strong>
            </div>
            <ul className="ccg-portal__list ccg-portal__list--files">
              <li>
                <a href="portal/auction-tracking-map.html" target="_blank" rel="noopener noreferrer" className="ccg-portal__file-link">
                  <i data-lucide="map" className="ccg-portal__file-icon"></i>
                  Interactive Map
                </a>
              </li>
            </ul>
          </div>
          {/* Dynamic deals from Supabase */}
          {deals.length > 0 && (
            <ul className="ccg-portal__list ccg-portal__list--deals">
              {deals.map(d => (
                <li key={d.id}><strong>{d.title}</strong><span className="ccg-portal__chip">{d.stage}</span></li>
              ))}
            </ul>
          )}
        </div>

        <div className="ccg-portal__card">
          <div className="ccg-portal__cardhead">
            <div className="ccg-eyebrow">Documents</div>
            <span className="ccg-portal__count">{docs.length}</span>
          </div>
          {docs.length === 0
            ? <p className="ccg-portal__muted">No documents shared yet.</p>
            : <ul className="ccg-portal__list">{docs.map(f => (
                <li key={f.id}>{f.name}</li>
              ))}</ul>}
        </div>
      </div>
    </section>
  );
}
window.PortalPage = PortalPage;

function App() {
  const [page, setPage] = React.useState('home');
  const [session, setSession] = React.useState(null);
  const [authReady, setAuthReady] = React.useState(false);
  const [partner, setPartner] = React.useState(null);

  React.useEffect(() => {
    if (!window.supabaseClient) { setAuthReady(true); return; }
    window.supabaseClient.auth.getSession().then(({ data }) => {
      setSession(data.session || null);
      setAuthReady(true);
    });
    const { data: sub } = window.supabaseClient.auth.onAuthStateChange((_event, s) => {
      setSession(s || null);
    });
    return () => sub.subscription.unsubscribe();
  }, []);

  // Load the partner row whenever the user changes; powers the Tap Map nav link.
  React.useEffect(() => {
    if (!session || !window.supabaseClient) { setPartner(null); return; }
    let cancelled = false;
    (async () => {
      const { data } = await window.supabaseClient
        .from('partners').select('*').eq('id', session.user.id).maybeSingle();
      if (!cancelled) setPartner(data || null);
    })();
    return () => { cancelled = true; };
  }, [session && session.user.id]);

  React.useEffect(() => {
    if (session && page === 'login') setPage('portal');
    if (!session && (page === 'portal' || page === 'tapmap')) setPage('home');
  }, [session]);

  React.useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, [page, session]);

  function nav(p) {
    if (p === 'login' && session) p = 'portal';
    if (p === 'tapmap' && (!partner || !partner.tap_map_access)) p = 'portal';
    setPage(p);
    window.scrollTo({ top: 0, behavior: 'instant' });
  }

  async function signOut() {
    if (window.supabaseClient) await window.supabaseClient.auth.signOut();
    setPage('home');
  }

  return (
    <div className="ccg-app">
      <Header active={page} onNav={nav} session={session} onSignOut={signOut} partner={partner} />
      <main className="ccg-main">
        {page === 'home' && <HomePage onNav={nav} />}
        {page === 'contact' && <ContactPage />}
        {page === 'login' && !session && <LoginPage onNav={nav} />}
        {page === 'login' && session && <PortalPage session={session} partner={partner} onSignOut={signOut} />}
        {page === 'portal' && session && <PortalPage session={session} partner={partner} onSignOut={signOut} />}
        {page === 'portal' && !session && authReady && <LoginPage onNav={nav} />}
        {page === 'tapmap' && session && <TapMapPage session={session} onSignOut={signOut} />}
        {page === 'tapmap' && !session && authReady && <LoginPage onNav={nav} />}
      </main>
      <Footer />
    </div>
  );
}
window.App = App;
