const { Icon } = window.PryzeDesignSystem_b2bad9;
const { Toast } = window.PryzeDesignSystem_b2bad9;
const { USER, REDEMPTIONS, REWARDS, COMPANIES } = window.PryzeData;
const { StatsContent } = window.PryzeStats;

function ProfileStat({ icon, value, label, color, coin }) {
  return (
    <div className="pf-stat">
      {coin ? <span className="pf-stat-coin"><Icon name="sparkle" size={12} weight="fill" color="var(--neutral-950)" /></span> : <Icon name={icon} weight="fill" size={18} color={color} />}
      <span className="pf-stat-value">{value}</span>
      <span className="pf-stat-label">{label}</span>
    </div>
  );
}

function ProfileRow({ icon, label, danger, onClick, external }) {
  return (
    <button className={"pf-row" + (danger ? " pf-row-danger" : "")} onClick={onClick}>
      <Icon name={icon} weight="regular" size={18} color={danger ? "var(--color-danger)" : "var(--fg-secondary)"} />
      <span className="pf-row-label">{label}</span>
      <Icon name={external ? "arrow-square-out" : "caret-right"} weight="bold" size={14} color="var(--fg-muted)" />
    </button>
  );
}

function PhotoSheet({ visible, onClose, onTakePhoto, onChoosePhoto, onRemove, hasPhoto }) {
  if (!visible) return null;
  return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">Profile photo</p>
        <button className="pf-sheet-opt" onClick={onTakePhoto}><Icon name="camera" weight="bold" size={18} color="var(--fg-primary)" />Take a photo</button>
        <button className="pf-sheet-opt" onClick={onChoosePhoto}><Icon name="image" weight="bold" size={18} color="var(--fg-primary)" />Choose from library</button>
        {hasPhoto && <button className="pf-sheet-opt pf-sheet-opt-danger" onClick={onRemove}><Icon name="trash" weight="bold" size={18} color="var(--color-danger)" />Delete photo</button>}
        <button className="pf-sheet-cancel" onClick={onClose}>Cancel</button>
      </div>
    </div>
  );
}

const STATUS_PRESETS = [
  "Chasing this month's goal 🎯",
  "Locked in and grinding 🔥",
  "Open to picking up shifts 🙌",
  "New here, say hi! 👋",
  "Saving up for something big 💸",
  "Streak mode: on 🚀",
  "Taking it easy this week 😌",
  "Top of the leaderboard 🏆",
];

function StatusSheet({ visible, current, onClose, onSelect }) {
  const [pick, setPick] = React.useState(current);
  const [own, setOwn] = React.useState('');
  React.useEffect(() => { if (visible) { setPick(current); setOwn(STATUS_PRESETS.includes(current) ? '' : current); } }, [visible, current]);
  if (!visible) return null;
  const value = own.trim() || pick;
  return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">Your status</p>
        <p className="pf-sheet-body">Everyone in your store sees this.</p>
        <div className="pf-status-grid">
          {STATUS_PRESETS.map(s => (
            <button key={s} className={"pf-status-chip" + (s === value ? " is-on" : "")} onClick={() => { setOwn(''); setPick(s); }}>{s}</button>
          ))}
        </div>
        <input className="pf-status-own" value={own} onChange={e => setOwn(e.target.value)} maxLength={48} placeholder="Or write your own…" />
        <button className="pf-status-save" disabled={!value} onClick={() => onSelect(value)}>Save status</button>
      </div>
    </div>
  );
}

function ConfirmSheet({ visible, title, body, confirmLabel, onConfirm, onClose }) {
  if (!visible) return null;
  return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">{title}</p>
        <p className="pf-sheet-body">{body}</p>
        <button className="pf-sheet-confirm-danger" onClick={onConfirm}>{confirmLabel}</button>
        <button className="pf-sheet-cancel" onClick={onClose}>Cancel</button>
      </div>
    </div>
  );
}

const EXIT_REASONS = ['Not using it enough', 'Rewards weren’t worth it', 'Switched jobs', 'Too many notifications', 'Something else'];

function DeleteAccountFlow({ visible, onClose, onDeleted }) {
  const [step, setStep] = React.useState('confirm');
  const [typed, setTyped] = React.useState('');
  const [reason, setReason] = React.useState(null);
  const [feedback, setFeedback] = React.useState('');

  React.useEffect(() => { if (visible) { setStep('confirm'); setTyped(''); setReason(null); setFeedback(''); } }, [visible]);

  if (!visible) return null;

  function submitFeedback() { setStep('goodbye'); }

  return (
    <div className="pf-sheet-overlay" onClick={step === 'goodbye' ? undefined : onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        {step === 'confirm' && (
          <React.Fragment>
            <p className="pf-sheet-title">Delete account?</p>
            <p className="pf-sheet-body">This permanently removes your <strong>profile</strong>, <strong>points</strong>, and <strong>redemption history</strong>. This can't be undone.</p>
            <p className="pf-sheet-label">Type <strong>DELETE</strong> to confirm</p>
            <input className="pf-sheet-input" value={typed} onChange={e => setTyped(e.target.value)} placeholder="DELETE" autoCapitalize="characters" />
            <button className="pf-sheet-cancel" onClick={onClose}>Cancel</button>
            <button className="pf-sheet-confirm-outline" disabled={typed.trim().toUpperCase() !== 'DELETE'} onClick={() => setStep('feedback')}>Delete my account</button>
          </React.Fragment>
        )}
        {step === 'feedback' && (
          <React.Fragment>
            <p className="pf-sheet-title">Before you go</p>
            <p className="pf-sheet-body">Tell us why you're leaving — this helps us improve.</p>
            <div className="pf-reason-list">
              {EXIT_REASONS.map(r => (
                <button key={r} className={"pf-reason-chip" + (reason === r ? " pf-reason-chip-active" : "")} onClick={() => setReason(r)}>{r}</button>
              ))}
            </div>
            <textarea className="pf-sheet-textarea" placeholder="Tell us more" value={feedback} onChange={e => setFeedback(e.target.value)} />
            <button className="pf-sheet-confirm-danger" disabled={!reason} onClick={submitFeedback}>Submit &amp; delete account</button>
          </React.Fragment>
        )}
        {step === 'goodbye' && (
          <React.Fragment>
            <div className="pf-goodbye-icon"><Icon name="heart" weight="fill" size={28} color="var(--color-primary)" /></div>
            <p className="pf-sheet-title">Sorry to see you go</p>
            <p className="pf-sheet-body">Your account and data have been deleted. Thanks for being part of Pryze — you're always welcome back.</p>
            <button className="pf-sheet-confirm-danger" style={{ background: 'var(--color-primary)' }} onClick={onDeleted}>Done</button>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

const LANGS = [{ k: 'en', label: 'English', note: 'English (US)' }, { k: 'es', label: 'Español', note: 'Español (Latinoamérica)' }];

const APPEARANCE = [
  { k: 'system', label: 'Automatic' },
  { k: 'light', label: 'Light' },
  { k: 'dark', label: 'Dark' },
];

function SettingsSheet({ visible, onClose, onDeleteAccount, lang, onLang, onToast, appearance, onAppearance }) {
  const [langOpen, setLangOpen] = React.useState(false);
  const [pane, setPane] = React.useState(null);
  const [push, setPush] = React.useState(true);
  React.useEffect(() => { if (!visible) { setLangOpen(false); setPane(null); } }, [visible]);
  if (!visible) return null;
  const current = LANGS.find(l => l.k === lang) || LANGS[0];
  if (pane === 'theme') return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">Appearance</p>
        <div className="pf-radio-list">
          {APPEARANCE.map(a => (
            <button key={a.k} className="pf-radio-row" onClick={() => onAppearance(a.k)}>
              <span className="pf-radio-label">{a.label}</span>
              <span className={'pf-radio' + (appearance === a.k ? ' is-on' : '')} />
            </button>
          ))}
        </div>
        <button className="pf-sheet-cancel" onClick={() => setPane(null)}>Back</button>
      </div>
    </div>
  );

  if (pane === 'notif') return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">Notifications</p>
        <div className="pf-notif-list">
          <div className="pf-notif">
            <span className="pf-notif-text"><b>Allow notifications</b></span>
            <button className={'pf-toggle' + (push ? ' is-on' : '')} onClick={() => setPush(v => !v)} aria-label="Allow notifications"><i /></button>
          </div>
        </div>
        <button className="pf-sheet-cancel" onClick={() => setPane(null)}>Back</button>
      </div>
    </div>
  );

  if (langOpen) return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">Language</p>
        <p className="pf-sheet-body">Pick the language for the whole app.</p>
        <div className="pf-lang-list">
          {LANGS.map(l => (
            <button key={l.k} className={'pf-lang-opt' + (l.k === lang ? ' pf-lang-opt-active' : '')} onClick={() => { onLang(l.k); setLangOpen(false); }}>
              <span className="pf-lang-main"><b>{l.label}</b><em>{l.note}</em></span>
              {l.k === lang && <Icon name="check-circle" weight="fill" size={20} color="var(--color-primary)" />}
            </button>
          ))}
        </div>
        <button className="pf-sheet-cancel" onClick={() => setLangOpen(false)}>Back</button>
      </div>
    </div>
  );
  return (
    <div className="pf-sheet-overlay" onClick={onClose}>
      <div className="pf-sheet" onClick={e => e.stopPropagation()}>
        <div className="pf-sheet-handle" />
        <p className="pf-sheet-title">Settings</p>
        <div className="pf-groups">
          <p className="pf-group-label">Preferences</p>
          <div className="pf-list">
            <ProfileRow icon="bell-ringing" label="Notifications" onClick={() => setPane('notif')} />
            <button className="pf-row" onClick={() => setPane('theme')}>
              <Icon name="moon-stars" weight="regular" size={18} color="var(--fg-secondary)" />
              <span className="pf-row-label">Appearance</span>
              <span className="pf-row-value">{(APPEARANCE.find(a => a.k === appearance) || APPEARANCE[1]).label}</span>
              <Icon name="caret-right" weight="bold" size={14} color="var(--fg-muted)" />
            </button>
            <button className="pf-row" onClick={() => setLangOpen(true)}>
              <Icon name="translate" weight="regular" size={18} color="var(--fg-secondary)" />
              <span className="pf-row-label">Language</span>
              <span className="pf-row-value">{current.label}</span>
              <Icon name="caret-right" weight="bold" size={14} color="var(--fg-muted)" />
            </button>
          </div>
          <p className="pf-group-label">Account</p>
          <div className="pf-list">
            <ProfileRow icon="lock-key" label="Change password" onClick={() => {}} />
            <ProfileRow icon="sign-out" label="Log out" onClick={() => {}} />
          </div>
          <p className="pf-group-label">Support &amp; legal</p>
          <div className="pf-list">
            <ProfileRow icon="question" label="FAQ" external onClick={() => window.open('https://pryzeapp.com/faq', '_blank')} />
            <ProfileRow icon="file-text" label="Terms &amp; conditions" external onClick={() => window.open('https://pryzeapp.com/terms', '_blank')} />
            <ProfileRow icon="shield-check" label="Privacy policy" external onClick={() => window.open('https://pryzeapp.com/privacy', '_blank')} />
          </div>
          <div className="pf-list pf-list-danger">
            <ProfileRow icon="trash" label="Delete account" danger onClick={onDeleteAccount} />
          </div>
        </div>
        <button className="pf-sheet-cancel" onClick={onClose}>Close</button>
      </div>
    </div>
  );
}

function ProfileScreen({ onAccountDeleted, onOpenCard, appearance, onAppearance }) {
  const [photo, setPhoto] = React.useState(USER.photo);
  const [photoSheet, setPhotoSheet] = React.useState(false);
  const [settingsSheet, setSettingsSheet] = React.useState(false);
  const [lang, setLang] = React.useState('en');
  const [deleteFlow, setDeleteFlow] = React.useState(false);
  const [view, setView] = React.useState('stats');
  const [status, setStatus] = React.useState(USER.status || STATUS_PRESETS[0]);
  const [statusSheet, setStatusSheet] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const cameraRef = React.useRef(null);
  const libraryRef = React.useRef(null);

  function handleFile(e) {
    const f = e.target.files && e.target.files[0];
    if (f) setPhoto(URL.createObjectURL(f));
    setPhotoSheet(false);
    e.target.value = '';
  }

  const initials = USER.name.split(' ').map(n => n[0]).join('').slice(0, 2);
  const company = USER.company && COMPANIES[USER.company];
  React.useEffect(() => { if (toast) { const t = setTimeout(() => setToast(null), 2600); return () => clearTimeout(t); } }, [toast]);

  return (
    <div className="screen-body pf-screen">
      <div className="pf-topbar">
        <span className="pf-topbar-title">Profile</span>
        <div className="pf-topbar-actions">
          <button className="pf-settings-btn" onClick={() => window.open('https://pryzeapp.com/support', '_blank')} aria-label="Chat with support"><Icon name="chat-circle-dots" weight="bold" size={20} color="var(--fg-primary)" /></button>
          <button className="pf-settings-btn" onClick={() => setSettingsSheet(true)} aria-label="Settings"><Icon name="gear-six" weight="bold" size={20} color="var(--fg-primary)" /></button>
        </div>
      </div>
      <div className="pf-hero-card">
        <div className="pf-hero-orbs" aria-hidden="true"><span></span><span></span><span></span></div>
        <div className="pf-hero-pattern" aria-hidden="true" />
        <button className="pf-hero-share" onClick={onOpenCard} aria-label="My card">
          <span className="pf-hero-share-glow" />
          <Icon name="share-network" size={14} weight="bold" color="#14170A" />
          My card
        </button>
        <div className="pf-hero-top">
          <div className="pf-avatar-wrap">
            {photo ? <img className="pf-avatar" src={photo} alt={USER.name} /> : <div className="pf-avatar pf-avatar-fallback">{initials}</div>}
            <button className="pf-avatar-edit" onClick={() => setPhotoSheet(true)} aria-label="Edit photo">
              <Icon name="pencil-simple" weight="fill" size={13} color="#4B3FC4" />
            </button>
          </div>
          <div className="pf-hero-info">
            <p className="pf-name">{USER.name}</p>
            <p className="pf-handle">{USER.role || 'Team member'}</p>
          </div>
        </div>
        <button className="pf-status-row" onClick={() => setStatusSheet(true)} aria-label="Edit status">
          <span className="pf-status-text">{status}</span>
          <span className="pf-status-edit">Edit</span>
          <Icon name="pencil-simple" weight="bold" size={12} color="rgba(255,255,255,.7)" />
        </button>
        <div className="pf-hero-divider" />
        <div className="pf-hero-company">
          {company && (company.logo ? <img className="pf-company-logo" src={company.logo} alt={company.name} /> : <span className="pf-company-logo pf-company-logo-fallback" style={{ background: company.bg }}>{company.initials}</span>)}
          <span className="pf-company-text">{USER.store}{company ? ` · ${company.name}` : ''}</span>
        </div>
      </div>

      <div className="pf-stats-row">
        <ProfileStat coin value={USER.points.toLocaleString()} label="Lifetime pts" color="var(--color-primary)" />
        <ProfileStat icon="heart" value={USER.kudos.toLocaleString()} label="Kudos" color="var(--pink-500, #E8547A)" />
        <ProfileStat icon="gift" value={REDEMPTIONS.length} label="Redeemed" color="var(--orange-500)" />
        <ProfileStat icon="target" value={USER.goals} label="Goals" color="#8B7FFF" />
      </div>

      <div className="pf-view-toggle">
        <button className={"pf-view-opt" + (view === 'stats' ? " pf-view-opt-active" : "")} onClick={() => setView('stats')}>Stats</button>
        <button className={"pf-view-opt" + (view === 'wallet' ? " pf-view-opt-active" : "")} onClick={() => setView('wallet')}>Rewards</button>
      </div>

      {view === 'stats' && (
        <div className="pf-section">
          <StatsContent />
        </div>
      )}

      {view === 'wallet' && (
      <div className="pf-section">
        <div className="pf-section-head">
          <p className="pf-section-title">Redemption history</p>
        </div>
        <div className="pf-wallet-list">
          {REDEMPTIONS.map(r => {
            const reward = REWARDS.find(x => x.id === r.rewardId);
            return (
              <div className="pf-wallet-row" key={r.id}>
                {reward.logo ? <div className="pf-wallet-logo pf-wallet-logo-img"><img src={reward.logo} alt={reward.title} /></div> : <div className="pf-wallet-logo" style={{ background: reward.bg }}>{reward.initials}</div>}
                <div className="pf-wallet-info">
                  <span className="pf-wallet-title">{reward.title}</span>
                  <span className="pf-wallet-date">{r.date}</span>
                </div>
                <span className="pf-wallet-amount">${r.amount}</span>
              </div>
            );
          })}
        </div>
      </div>
      )}

      <StatusSheet visible={statusSheet} current={status} onClose={() => setStatusSheet(false)} onSelect={s => { setStatus(s); setStatusSheet(false); }} />
      {toast && <div className="pf-toast-wrap"><Toast message={toast} /></div>}
      <input ref={cameraRef} type="file" accept="image/*" capture="environment" style={{ display: 'none' }} onChange={handleFile} />
      <input ref={libraryRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleFile} />
      <PhotoSheet visible={photoSheet} hasPhoto={!!photo}
        onTakePhoto={() => cameraRef.current && cameraRef.current.click()}
        onChoosePhoto={() => libraryRef.current && libraryRef.current.click()}
        onRemove={() => { setPhoto(null); setPhotoSheet(false); setToast('Profile photo removed'); }}
        onClose={() => setPhotoSheet(false)} />
      <SettingsSheet visible={settingsSheet} onClose={() => setSettingsSheet(false)} onToast={setToast} appearance={appearance} onAppearance={onAppearance} lang={lang} onLang={k => { setLang(k); setToast(k === 'es' ? 'Idioma cambiado a Español' : 'Language set to English'); }} onDeleteAccount={() => { setSettingsSheet(false); setDeleteFlow(true); }} />
      <DeleteAccountFlow visible={deleteFlow} onClose={() => setDeleteFlow(false)} onDeleted={() => { setDeleteFlow(false); onAccountDeleted && onAccountDeleted(); }} />
    </div>
  );
}

function LoginScreen() {
  return (
    <div className="placeholder">
      <div className="big">👋</div>
      <p className="section-title" style={{fontSize:15,textTransform:'none',letterSpacing:0,color:'var(--fg-primary)',fontWeight:700}}>Log in / Sign up</p>
      <p style={{fontSize:13}}>This flow is coming in a later phase.</p>
    </div>
  );
}

window.PryzeProfile = { ProfileScreen, LoginScreen };
