// Mock auth + plan + usage tracking. Pretends to be a server but stored in localStorage.
// In production this would be replaced by real Clerk + Postgres calls.

const PLAN_LIMITS = {
  anon: {
    label: 'Guest',
    maxCategoriesPerType: Infinity,
    canCopy: true,
    canSave: true,
    canExport: true,
    canAIEnhance: true,
    aiEnhancePerDay: Infinity,
    canAIThumbs: true,
    aiThumbsPerDay: Infinity,
    watermark: false,
    bigCategoriesUnlocked: true,
  },
  free: {
    label: 'Free',
    maxCategoriesPerType: 6,
    canCopy: true,
    canSave: true,
    canExport: false,
    canAIEnhance: true,
    aiEnhancePerDay: 5,
    canAIThumbs: true,
    aiThumbsPerDay: 30,
    watermark: true,
    bigCategoriesUnlocked: false,
  },
  pro: {
    label: 'Pro',
    maxCategoriesPerType: Infinity,
    canCopy: true,
    canSave: true,
    canExport: true,
    canAIEnhance: true,
    aiEnhancePerDay: Infinity,
    canAIThumbs: true,
    aiThumbsPerDay: Infinity,
    watermark: false,
    bigCategoriesUnlocked: true,
  },
};

const PRICING = {
  monthly: { price: 4.99, currency: 'USD', label: '$4.99/mo' },
  yearly:  { price: 39,    currency: 'USD', label: '$39/yr', saved: 'Save 35%' },
};

function todayKey() {
  const d = new Date();
  return `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`;
}

// ─── useAuth: state hook ───────────────────────────────────────────
function useAuth() {
  const [user, setUser] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('autoprompt:user') || 'null'); }
    catch { return null; }
  });
  const [usage, setUsage] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('autoprompt:usage') || '{}'); }
    catch { return {}; }
  });

  React.useEffect(() => {
    if (user) localStorage.setItem('autoprompt:user', JSON.stringify(user));
    else localStorage.removeItem('autoprompt:user');
  }, [user]);
  React.useEffect(() => {
    localStorage.setItem('autoprompt:usage', JSON.stringify(usage));
  }, [usage]);

  // Sign in — mock with 600ms fake server delay
  const signIn = async (method, email) => {
    await new Promise(r => setTimeout(r, 600));
    const u = {
      id: 'u_' + Math.random().toString(36).slice(2, 10),
      email: email || (method === 'google' ? 'you@gmail.com' : method === 'facebook' ? 'you@fb.com' : 'you@example.com'),
      method,
      plan: 'free',
      joinedAt: Date.now(),
      name: email ? email.split('@')[0] : 'You',
    };
    setUser(u);
    return u;
  };
  const signOut = () => { setUser(null); };
  const upgrade = async () => {
    await new Promise(r => setTimeout(r, 800));
    setUser(u => u ? { ...u, plan: 'pro', proSince: Date.now() } : u);
  };
  const downgrade = () => {
    setUser(u => u ? { ...u, plan: 'free', proSince: null } : u);
  };

  const planId = user?.plan || 'anon';
  const limits = PLAN_LIMITS[planId];

  // Usage check + increment helpers — daily reset
  const bump = (key) => {
    const k = todayKey();
    setUsage(u => ({ ...u, [`${k}:${key}`]: (u[`${k}:${key}`] || 0) + 1 }));
  };
  const usedToday = (key) => usage[`${todayKey()}:${key}`] || 0;
  const remaining = (key, max) => {
    if (max === Infinity) return Infinity;
    return Math.max(0, max - usedToday(key));
  };

  return {
    user, planId, limits, usage,
    signIn, signOut, upgrade, downgrade,
    bump, usedToday, remaining,
    PRICING,
  };
}

// ─── SignInModal ──────────────────────────────────────────────────
function SignInModal({ open, onClose, onSignIn, reason }) {
  const [busy, setBusy] = React.useState(null); // 'google' | 'facebook' | 'email'
  const [email, setEmail] = React.useState('');
  const [showEmail, setShowEmail] = React.useState(false);
  if (!open) return null;

  const go = async (method) => {
    setBusy(method);
    try { await onSignIn(method, method === 'email' ? email : null); onClose(); }
    finally { setBusy(null); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}><Ico name="close" size={18}/></button>
        <div className="modal-brand">
          <div className="modal-brand-mark">✦</div>
          <div className="modal-brand-name">Autoprompt</div>
        </div>
        <h2 className="modal-title">Sign in</h2>
        {reason && <p className="modal-reason">{reason}</p>}
        <p className="modal-sub">Free forever. ไม่ต้องใส่บัตร, ใช้ได้ทันที.</p>

        <div className="auth-buttons">
          <button className="auth-btn" disabled={!!busy} onClick={() => go('google')}>
            <span className="auth-ico g">G</span>
            <span>{busy === 'google' ? 'Signing in…' : 'Continue with Google'}</span>
          </button>
          <button className="auth-btn" disabled={!!busy} onClick={() => go('facebook')}>
            <span className="auth-ico f">f</span>
            <span>{busy === 'facebook' ? 'Signing in…' : 'Continue with Facebook'}</span>
          </button>
          {!showEmail ? (
            <button className="auth-btn" disabled={!!busy} onClick={() => setShowEmail(true)}>
              <span className="auth-ico e"><Ico name="mail" size={14}/></span>
              <span>Continue with Email</span>
            </button>
          ) : (
            <form onSubmit={(e) => { e.preventDefault(); if (email.includes('@')) go('email'); }}>
              <div className="auth-email-row">
                <input type="email" placeholder="you@example.com" required
                  value={email} onChange={(e) => setEmail(e.target.value)}
                  className="auth-email-input"/>
                <button type="submit" className="btn primary" disabled={!email.includes('@') || !!busy}>
                  {busy === 'email' ? '…' : 'Send'}
                </button>
              </div>
              <p className="modal-sub">เราจะส่ง magic link ไปทาง email (จำลอง — กดส่งแล้ว sign in ทันที)</p>
            </form>
          )}
        </div>

        <p className="modal-fine">By signing in you agree to our Terms & Privacy. We store only your email and saved prompts — nothing else.</p>
      </div>
    </div>
  );
}

// ─── PricingModal ──────────────────────────────────────────────────
function PricingModal({ open, onClose, user, onUpgrade, onSignInFirst }) {
  const [busy, setBusy] = React.useState(false);
  const [billing, setBilling] = React.useState('monthly');
  if (!open) return null;

  const isPro = user?.plan === 'pro';

  const go = async () => {
    if (!user) { onSignInFirst(); return; }
    setBusy(true);
    try { await onUpgrade(); onClose(); }
    finally { setBusy(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal-pricing" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}><Ico name="close" size={18}/></button>
        <h2 className="modal-title">Choose your plan</h2>
        <p className="modal-sub">Cancel anytime. ไม่มี contract, ไม่มี hidden fees.</p>

        <div className="billing-toggle">
          <button className={cn('bill-tab', billing === 'monthly' && 'active')} onClick={() => setBilling('monthly')}>Monthly</button>
          <button className={cn('bill-tab', billing === 'yearly' && 'active')} onClick={() => setBilling('yearly')}>
            Yearly <span className="bill-save">Save 35%</span>
          </button>
        </div>

        <div className="plan-grid">
          <PlanCard name="Free" price="$0" period="forever"
            features={[
              '6 categories per output type',
              '5 AI enhance / day',
              '30 AI image previews / day',
              'Save up to 50 prompts',
              { text: 'No export', strike: true },
              { text: '"Made with Autoprompt" watermark', strike: true },
            ]}
            current={user?.plan === 'free'}
            cta={!user ? 'Sign in (free)' : (user.plan === 'free' ? 'Current plan' : 'Downgrade')}
            onClick={() => { if (!user) onSignInFirst(); }}
          />
          <PlanCard name="Pro" price={billing === 'monthly' ? '$4.99' : '$39'} period={billing === 'monthly' ? '/month' : '/year'}
            featured
            features={[
              { text: 'Unlimited categories — incl. 1,000+ hair & body presets', highlight: true },
              { text: 'Unlimited AI enhance', highlight: true },
              { text: 'Unlimited AI image previews', highlight: true },
              'Save unlimited prompts + folders',
              'Export to JSON / CSV',
              'No watermark',
              'Share via permalink',
            ]}
            current={isPro}
            cta={isPro ? 'Current plan ✓' : (busy ? 'Upgrading…' : 'Upgrade to Pro')}
            onClick={isPro ? null : go}
          />
        </div>

        <p className="modal-fine">
          💡 <strong>Demo:</strong> This is a UI mockup. "Upgrade" instantly flips your plan to Pro — no actual payment is processed.
        </p>
      </div>
    </div>
  );
}

function PlanCard({ name, price, period, features, current, cta, onClick, featured }) {
  return (
    <div className={cn('plan-card', featured && 'featured', current && 'current')}>
      {featured && <div className="plan-ribbon">Most popular</div>}
      <h3 className="plan-name">{name}</h3>
      <div className="plan-price">
        <span className="plan-amount">{price}</span>
        <span className="plan-period">{period}</span>
      </div>
      <ul className="plan-features">
        {features.map((f, i) => {
          const obj = typeof f === 'string' ? { text: f } : f;
          return (
            <li key={i} className={cn(obj.strike && 'strike', obj.highlight && 'hi')}>
              {obj.strike ? '×' : obj.highlight ? '★' : '✓'} {obj.text}
            </li>
          );
        })}
      </ul>
      <button className={cn('btn', featured ? 'accent' : 'primary', 'plan-cta')} disabled={!onClick} onClick={onClick || undefined}>
        {cta}
      </button>
    </div>
  );
}

// ─── Lock / Upgrade lockup ──────────────────────────────────────────
function Lock({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" style={{ display: 'inline-block', verticalAlign: 'middle', flexShrink: 0 }}>
      <rect x="3" y="7" width="10" height="7" rx="1.5" fill="none" stroke="currentColor" strokeWidth="1.5"/>
      <path d="M 5 7 V 5 a 3 3 0 0 1 6 0 V 7" fill="none" stroke="currentColor" strokeWidth="1.5"/>
      <circle cx="8" cy="10.5" r="1" fill="currentColor"/>
    </svg>
  );
}

Object.assign(window, {
  useAuth, SignInModal, PricingModal, PlanCard, Lock,
  PLAN_LIMITS, PRICING,
});
