/* eslint-disable */

// ─── Home Page ────────────────────────────────────────────────────────────────
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 Page ────────────────────────────────────────────────────────────
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;

// ─── Login Page ───────────────────────────────────────────────────────────────
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);
  }

  const [showEmail, setShowEmail] = React.useState(false);

  async function signInWithGoogle() {
    if (!window.supabaseClient) return;
    setBusy(true);
    await window.supabaseClient.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo: window.location.origin + '/' }
    });
    setBusy(false);
  }

  const GoogleIcon = () => (
    <svg width="20" height="20" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg" style={{flexShrink:0}}>
      <path d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" fill="#4285F4"/>
      <path d="M9 18c2.43 0 4.467-.806 5.956-2.184l-2.908-2.258c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" fill="#34A853"/>
      <path d="M3.964 10.707A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.707V4.961H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.039l3.007-2.332z" fill="#FBBC05"/>
      <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.961L3.964 7.293C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
    </svg>
  );

  const EmailIcon = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}>
      <rect x="2" y="4" width="20" height="16" rx="2"/>
      <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>
    </svg>
  );

  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>

        <div className="ccg-login__providers">
          <button className="ccg-auth-btn" onClick={signInWithGoogle} disabled={busy} type="button">
            <GoogleIcon />
            <span>Continue with Google</span>
          </button>

          <button className="ccg-auth-btn" onClick={() => setShowEmail(!showEmail)} disabled={busy} type="button">
            <EmailIcon />
            <span>Sign in with Email</span>
          </button>
        </div>

        {showEmail && (
          <form className="ccg-login__form ccg-login__form--reveal" 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.</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;

// ─── Project Card ─────────────────────────────────────────────────────────────
// icon names are Lucide icon strings; thumbnail_url is optional image
const PROJECT_ICONS = {
  'map':        'map-pin',
  'spreadsheet':'table-2',
  'property':   'building-2',
  'document':   'file-text',
  'analysis':   'bar-chart-3',
  'default':    'folder-open',
};

function ProjectCard({ deal }) {
  const title       = deal.title        || 'Untitled Project';
  const stage       = deal.stage        || 'Active';
  const url         = deal.url          || null;
  const description = deal.description  || '';
  const iconKey     = deal.icon_key     || 'default';
  const thumbnail   = deal.thumbnail_url|| null;
  const lucideIcon  = PROJECT_ICONS[iconKey] || PROJECT_ICONS['default'];

  const isActive  = stage === 'Active';
  const chipClass = isActive ? 'ccg-project__chip--active' : 'ccg-project__chip--inactive';

  function openProject(e) {
    e.preventDefault();
    if (url) window.open(url, '_blank', 'noopener,noreferrer');
  }

  return (
    <article className={'ccg-project' + (url ? ' ccg-project--linked' : '')} onClick={url ? openProject : undefined}>
      <div className="ccg-project__thumb">
        {thumbnail
          ? <img src={thumbnail} alt={title} className="ccg-project__img" />
          : <div className="ccg-project__icon-wrap"><i data-lucide={lucideIcon}></i></div>
        }
      </div>
      <div className="ccg-project__body">
        <div className="ccg-project__head">
          <h3 className="ccg-project__title">{title}</h3>
          <span className={'ccg-project__chip ' + chipClass}>{stage}</span>
        </div>
        {description ? <p className="ccg-project__desc">{description}</p> : null}
        {url ? (
          <a href={url} target="_blank" rel="noopener noreferrer"
             className="ccg-project__open" onClick={(e) => e.stopPropagation()}>
            Open Project <i data-lucide="arrow-up-right"></i>
          </a>
        ) : (
          <span className="ccg-project__pending">Link coming soon</span>
        )}
      </div>
    </article>
  );
}
window.ProjectCard = ProjectCard;

// ─── Project List (handles flat + folder grouping) ───────────────────────────
function ProjectFolder({ name, deals }) {
  const [open, setOpen] = React.useState(true);
  return (
    <div className="ccg-project-folder">
      <button className="ccg-project-folder__header" onClick={() => setOpen(o => !o)}>
        <i data-lucide={open ? 'folder-open' : 'folder'}></i>
        <span className="ccg-project-folder__name">{name}</span>
        <span className="ccg-project-folder__count">{deals.length}</span>
        <i data-lucide={open ? 'chevron-down' : 'chevron-right'} className="ccg-project-folder__chevron"></i>
      </button>
      {open && (
        <div className="ccg-project-grid ccg-project-grid--inset">
          {deals.map(d => <ProjectCard key={d.id} deal={d} />)}
        </div>
      )}
    </div>
  );
}
window.ProjectFolder = ProjectFolder;

function ProjectList({ deals }) {
  // Separate ungrouped from grouped
  const ungrouped = deals.filter(d => !d.folder);
  const folders   = deals.reduce((acc, d) => {
    if (!d.folder) return acc;
    if (!acc[d.folder]) acc[d.folder] = [];
    acc[d.folder].push(d);
    return acc;
  }, {});

  return (
    <div className="ccg-project-section">
      {/* Folder groups first */}
      {Object.entries(folders).map(([name, items]) => (
        <ProjectFolder key={name} name={name} deals={items} />
      ))}
      {/* Ungrouped cards */}
      {ungrouped.length > 0 && (
        <div className="ccg-project-grid">
          {ungrouped.map(d => <ProjectCard key={d.id} deal={d} />)}
        </div>
      )}
    </div>
  );
}
window.ProjectList = ProjectList;

// ─── Portal Page ──────────────────────────────────────────────────────────────
function PortalPage({ session, onSignOut }) {
  const [partner, setPartner] = React.useState(null);
  const [deals, setDeals]     = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!session || !window.supabaseClient) return;
    (async () => {
      const sb = window.supabaseClient;
      const [{ data: p }, { data: d }] = await Promise.all([
        sb.from('partners').select('*').eq('id', session.user.id).maybeSingle(),
        sb.from('deals').select('*').eq('partner_id', session.user.id).order('sort_order', { ascending: true }),
      ]);
      setPartner(p || null);
      setDeals(d || []);
      setLoading(false);
    })();
  }, [session && session.user.id]);

  React.useEffect(() => {
    // Re-run Lucide icon rendering after projects load
    if (!loading && window.lucide) window.lucide.createIcons();
  }, [loading, deals]);

  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">
      {/* ── Header ── */}
      <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>

      {/* ── Profile strip ── */}
      <div className="ccg-portal__profile-strip">
        <dl className="ccg-portal__defs ccg-portal__defs--row">
          <dt>Email</dt>    <dd>{session.user.email}</dd>
          <dt>Company</dt>  <dd>{(partner && partner.company) || <span className="ccg-portal__muted">—</span>}</dd>
          <dt>Phone</dt>    <dd>{(partner && partner.phone)   || <span className="ccg-portal__muted">—</span>}</dd>
        </dl>
      </div>

      {/* ── Projects ── */}
      <div className="ccg-portal__projects-hd">
        <div className="ccg-eyebrow">Your Projects</div>
        <span className="ccg-portal__count">{deals.length}</span>
      </div>

      {deals.length === 0 ? (
        <div className="ccg-portal__empty">
          <i data-lucide="folder-open"></i>
          <p>No projects yet. Ross will add your engagements here.</p>
        </div>
      ) : (
        <ProjectList deals={deals} />
      )}
    </section>
  );
}
window.PortalPage = PortalPage;

// ─── App shell ────────────────────────────────────────────────────────────────
function App() {
  const [page, setPage] = React.useState(() => {
    // Support direct URL navigation e.g. /login, /portal, /contact
    const path = window.location.pathname.replace(/^\//, '').split('/')[0];
    return ['login', 'portal', 'contact'].includes(path) ? path : 'home';
  });
  const [session, setSession]   = React.useState(null);
  const [authReady, setAuthReady] = React.useState(false);

  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();
  }, []);

  React.useEffect(() => {
    if (!authReady) return;  // wait for session check before redirecting
    if (session && (page === 'login' || page === 'home')) setPage('portal');
    if (!session && page === 'portal') setPage('home');
  }, [session, authReady]);

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

  function nav(p) {
    if (p === 'login' && session) 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} />
      <main className="ccg-main">
        {page === 'home'   && <HomePage onNav={nav} />}
        {page === 'contact' && <ContactPage />}
        {page === 'login'  && !session && <LoginPage onNav={nav} />}
        {page === 'login'  &&  session && <PortalPage session={session} onSignOut={signOut} />}
        {page === 'portal' &&  session && <PortalPage session={session} onSignOut={signOut} />}
        {page === 'portal' && !session && authReady && <LoginPage onNav={nav} />}
      </main>
      <Footer />
    </div>
  );
}
window.App = App;
