/* acme-app.jsx — Main app with routing, state, animations, and tweaks */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "model": "acme-credit-v3.2",
  "showMetadata": true,
  "animateScoring": true
}/*EDITMODE-END*/;

const AcmeApp = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = React.useState('dashboard'); // 'dashboard' | 'applications'
  const [selectedIdx, setSelectedIdx] = React.useState(0);
  const [phase, setPhase] = React.useState('done');
  const [factorsVisible, setFactorsVisible] = React.useState(true);
  const [decisionVisible, setDecisionVisible] = React.useState(true);
  const phaseRef = React.useRef('done');

  const app = APPLICANTS[selectedIdx];
  const model = MODELS[t.model] || MODELS['acme-credit-v3.2'];

  const handleNavClick = (tab) => {
    if (tab === 'Dashboard') setView('dashboard');
    else if (tab === 'Applications') setView('applications');
  };

  const handleOpenApplication = (idx) => {
    setSelectedIdx(idx);
    setView('applications');
    // Reset animation state for fresh entry
    setFactorsVisible(true);
    setDecisionVisible(true);
    setPhase('done');
    phaseRef.current = 'done';
    if (t.animateScoring) {
      setFactorsVisible(false);
      setDecisionVisible(false);
      setPhase('loading');
      phaseRef.current = 'loading';
      setTimeout(() => {
        if (phaseRef.current === 'loading') {
          setPhase('animating');
          phaseRef.current = 'animating';
          setTimeout(() => {
            setFactorsVisible(true);
            setTimeout(() => {
              setDecisionVisible(true);
              setPhase('done');
              phaseRef.current = 'done';
            }, 600);
          }, 800);
        }
      }, 1200);
    }
  };

  const handleSidebarSelect = (idx) => {
    if (idx === selectedIdx) return;
    handleOpenApplication(idx);
  };

  const isLoading = phase === 'loading';
  const isAnimating = phase === 'loading';
  const activeTab = view === 'dashboard' ? 'Dashboard' : 'Applications';

  return (
    <div style={{ width: '100vw', height: '100vh', background: ACME.bg, fontFamily: ACME.font, color: ACME.text, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <style>{`@keyframes acme-spin { to { transform: rotate(360deg); } }`}</style>
      <AcmeNav activeTab={activeTab} onTabClick={handleNavClick} />

      {view === 'dashboard' ? (
        <AcmeDashboard onOpenApplication={handleOpenApplication} model={model} />
      ) : (
        <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
          <AcmeSidebar applicants={APPLICANTS} selectedIndex={selectedIdx} onSelect={handleSidebarSelect} />

          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            <AcmeBreadcrumb appId={app.id} />

            <div style={{ flex: 1, display: 'flex', padding: '0 24px 20px', gap: 20, overflow: 'hidden' }}>
              {/* ─── Left Panel ─── */}
              <div style={{ flex: '1 1 55%', display: 'flex', flexDirection: 'column', gap: 16, overflow: 'auto', paddingRight: 4 }}>
                {/* Header */}
                <div style={{ background: ACME.card, borderRadius: 12, padding: '20px 24px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    <div style={{ width: 48, height: 48, borderRadius: 12, background: '#F0FDF4', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 700, color: ACME.primary }}>{app.initials}</div>
                    <div>
                      <div style={{ fontSize: 18, fontWeight: 700 }}>{app.name}</div>
                      <div style={{ fontSize: 13, color: ACME.muted, display: 'flex', gap: 8, marginTop: 2, flexWrap: 'wrap' }}>
                        <span>{app.id}</span><span>·</span><span>{app.product}</span><span>·</span><span>Submitted {app.submitted}</span>
                      </div>
                    </div>
                  </div>
                  <StatusBadge type={app.decisionType} />
                </div>

                <InfoSection title="Personal Information">
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px 24px' }}>
                    <InfoField label="Full Name" value={app.name} />
                    <InfoField label="SSN" value={app.ssn} />
                    <InfoField label="Date of Birth" value={app.dob} />
                    <InfoField label="Phone" value={app.phone} />
                    <InfoField label="Email" value={app.email} />
                    <InfoField label="Address" value={app.address} />
                  </div>
                </InfoSection>

                <InfoSection title="Employment & Income">
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px 24px' }}>
                    <InfoField label="Employer" value={app.employer} />
                    <InfoField label="Title" value={app.title} />
                    <InfoField label="Tenure" value={app.yearsEmployed} />
                    <InfoField label="Annual Income" value={app.income} />
                    <InfoField label="Other Income" value={app.additionalIncome} />
                    <InfoField label="Total Monthly" value={app.totalMonthly} />
                  </div>
                </InfoSection>

                <InfoSection title="Loan Request">
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '16px 24px' }}>
                    <InfoField label="Product" value={app.product} />
                    <InfoField label="Amount" value={app.amount} />
                    <InfoField label="Property Value" value={app.propertyValue} />
                    <InfoField label="Current Mortgage" value={app.currentMortgage} />
                    <InfoField label="Combined LTV" value={app.ltv} />
                    <InfoField label="Purpose" value={app.purpose} />
                  </div>
                </InfoSection>
              </div>

              {/* ─── Right Panel ─── */}
              <div style={{ flex: '1 1 45%', display: 'flex', flexDirection: 'column', gap: 14, overflow: 'auto', paddingRight: 4 }}>
                {/* Score */}
                <div style={{ background: ACME.card, borderRadius: 12, padding: 24, textAlign: 'center', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: ACME.muted, textTransform: 'uppercase', letterSpacing: 1.2, marginBottom: 4 }}>Credit Assessment</div>
                  {isLoading ? (
                    <ScoringLoader />
                  ) : (
                    <React.Fragment>
                      <AcmeGauge targetScore={app.score} min={300} max={850} label={app.scoreLabel} isAnimating={isAnimating} />
                      <div style={{ marginTop: 12 }}>
                        <DecisionBadge decision={app.decision} type={app.decisionType} visible={decisionVisible} />
                      </div>
                    </React.Fragment>
                  )}
                </div>

                {/* Factors */}
                {!isLoading && (
                  <div style={{ background: ACME.card, borderRadius: 12, padding: 20, boxShadow: '0 1px 3px rgba(0,0,0,0.06)', flex: 1 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: ACME.muted, textTransform: 'uppercase', letterSpacing: 1.2, marginBottom: 14 }}>Contributing Factors</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {app.factors.map((f, i) => (
                        <FactorCard key={i} factor={f} visible={factorsVisible} delay={i * 80} />
                      ))}
                    </div>
                  </div>
                )}

                {/* Conditions */}
                {!isLoading && app.conditions.length > 0 && (
                  <div style={{ background: '#FFFBEB', borderRadius: 12, padding: '14px 18px', opacity: factorsVisible ? 1 : 0, transition: 'opacity 0.4s ease 0.4s' }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: '#B45309', marginBottom: 6 }}>Conditions for Approval</div>
                    {app.conditions.map((c, i) => (
                      <div key={i} style={{ fontSize: 12, color: '#92400E', padding: '3px 0', display: 'flex', gap: 6 }}><span style={{ color: '#D97706' }}>{i + 1}.</span>{c}</div>
                    ))}
                  </div>
                )}

                {/* Actions */}
                {!isLoading && (
                  <div style={{ display: 'flex', gap: 10, opacity: decisionVisible ? 1 : 0, transition: 'opacity 0.3s ease' }}>
                    {app.decisionType !== 'declined' && (
                      <button style={{ flex: 1, padding: '11px 0', background: ACME.primary, color: '#fff', border: 'none', borderRadius: 10, fontSize: 14, fontWeight: 600, fontFamily: ACME.font, cursor: 'pointer' }}>Approve</button>
                    )}
                    <button style={{ flex: 1, padding: '11px 0', background: '#fff', color: ACME.text, border: '1px solid ' + ACME.border, borderRadius: 10, fontSize: 14, fontWeight: 500, fontFamily: ACME.font, cursor: 'pointer' }}>Committee</button>
                    <button style={{ flex: 1, padding: '11px 0', background: '#fff', color: ACME.text, border: '1px solid ' + ACME.border, borderRadius: 10, fontSize: 14, fontWeight: 500, fontFamily: ACME.font, cursor: 'pointer' }}>Request Info</button>
                    <button style={{ padding: '11px 16px', background: '#FEF2F2', color: '#DC2626', border: '1px solid #FECACA', borderRadius: 10, fontSize: 14, fontWeight: 500, fontFamily: ACME.font, cursor: 'pointer' }}>Decline</button>
                  </div>
                )}
              </div>
            </div>

            {/* Footer */}
            {t.showMetadata && (
              <div style={{ padding: '8px 24px', fontSize: 11, color: ACME.subtle, borderTop: '1px solid ' + ACME.border, background: '#fff', display: 'flex', justifyContent: 'space-between', flexShrink: 0 }}>
                <span>Model: {t.model} ({model.label}) · Inference: {app.inference} · Confidence: {app.confidence}</span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <div style={{ width: 6, height: 6, borderRadius: 3, background: '#10B981' }}></div>
                  {model.engine}
                </span>
              </div>
            )}
          </div>
        </div>
      )}

      <TweaksPanel>
        <TweakSection label="Model" />
        <TweakSelect label="Scoring Model" value={t.model}
          options={Object.keys(MODELS).map(k => ({ value: k, label: MODELS[k].label }))}
          onChange={(v) => setTweak('model', v)} />
        <TweakSection label="Demo" />
        <TweakToggle label="Scoring animation" value={t.animateScoring}
          onChange={(v) => setTweak('animateScoring', v)} />
        <TweakToggle label="Show AI metadata" value={t.showMetadata}
          onChange={(v) => setTweak('showMetadata', v)} />
      </TweaksPanel>
    </div>
  );
};

/* Small status badge for the applicant header */
const StatusBadge = ({ type }) => {
  const map = {
    'approved-conditions': { bg: '#FEF3C7', color: '#B45309', dot: '#F59E0B', label: 'Under Review' },
    'review': { bg: '#DBEAFE', color: '#1D4ED8', dot: '#3B82F6', label: 'Pending Review' },
    'approved': { bg: '#D1FAE5', color: '#065F46', dot: '#10B981', label: 'Approved' },
    'declined': { bg: '#FEE2E2', color: '#991B1B', dot: '#EF4444', label: 'Declined' },
  };
  const s = map[type] || map['review'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 14px', borderRadius: 20, background: s.bg, fontSize: 12, fontWeight: 600, color: s.color, fontFamily: ACME.font }}>
      <div style={{ width: 6, height: 6, borderRadius: 3, background: s.dot }}></div>
      {s.label}
    </div>
  );
};

window.AcmeApp = AcmeApp;
