/* global React, Button, Icon, LoadingSpinner, OnboardingProgress, PlanPicker, PlanLimitMeter, apiFetch, formatDateTime, useApiResource, useAuth, usePlans, validateBrowserReturnPath, getPlanLimitState, workflowMinIntervalSeconds, isPublicBillingPeriod, publicBillingPeriodOrDefault */
const { useState: useStateBilling } = React;

function SettingsBillingPage({ navigate }) {
  const auth = useAuth();
  const summary = useApiResource('/api/billing/summary');
  const [message, setMessage] = useStateBilling('');
  const [busyAction, setBusyAction] = useStateBilling('');
  const [cancelStep, setCancelStep] = useStateBilling('idle');
  const [cancelReason, setCancelReason] = useStateBilling('');
  const [period, setPeriod] = useStateBilling('monthly');
  const [choosingPlan, setChoosingPlan] = useStateBilling('');
  const plans = usePlans(period);
  const billing = summary.data?.billing;
  const currentPlanId = billing?.current_plan || auth?.me?.organization?.currentPlan || '';
  const currentBillingPeriod = billing?.billing_period || auth?.me?.organization?.billingPeriod || '';
  const subscriptionStatus = billing?.subscription_status || auth?.me?.organization?.subscriptionStatus || 'unpaid';
  const canManageExistingSubscription = ['active', 'trialing', 'past_due'].includes(subscriptionStatus);
  const isRefundFlow = cancelStep === 'refund';
  const flowTitle = isRefundFlow ? 'Refund and cancel subscription' : 'Before you cancel';
  const flowBadgeClass = isRefundFlow ? 'badge-fail' : 'badge-pending';
  const flowBadgeLabel = isRefundFlow ? 'Refund path' : 'Cancellation path';
  const flowDescription = isRefundFlow
    ? 'You can still take the save offer, or continue to refund the latest eligible charge and cancel the subscription.'
    : 'Take 50% off one month, or tell us what we missed and continue with cancellation.';
  const flowMetricLabel = isRefundFlow ? 'Refund until' : 'Current plan';
  const flowMetricValue = isRefundFlow
    ? formatDateTime(billing?.refund_eligible_until)
    : (billing?.current_plan || 'No plan');
  const finalActionLabel = isRefundFlow ? 'Refund and cancel' : 'Cancel anyway';

  if (auth?.me?.role !== 'owner') {
    return (
      <div className="card settings-card">
        <h2>Billing</h2>
        <p className="muted">Only the workspace owner can view billing.</p>
      </div>
    );
  }

  async function run(action, key) {
    setBusyAction(key);
    setMessage('');
    try {
      await action();
      await summary.reload();
    } catch (error) {
      setMessage(error.message);
    } finally {
      setBusyAction('');
    }
  }

  function settingsReturnPath() {
    const browserPath = window.location.pathname && window.location.pathname !== '/'
      ? `${window.location.pathname}${window.location.search || ''}`
      : '/settings/billing';
    const queryIndex = browserPath.indexOf('?');
    if (queryIndex >= 0) {
      const params = new URLSearchParams(browserPath.slice(queryIndex + 1));
      const nestedReturnTo = validateBrowserReturnPath(params.get('return_to'));
      if (nestedReturnTo) return nestedReturnTo;
    }
    const basePath = queryIndex >= 0 ? browserPath.slice(0, queryIndex) : browserPath;
    return validateBrowserReturnPath(basePath) || '/settings/billing';
  }

  async function choosePlan(planId, plan = null, options = {}) {
    if (auth?.me?.role !== 'owner') {
      setMessage('Only the workspace owner can choose a plan.');
      return;
    }
    if (plan?.contactSales) {
      window.openCustomPlanCta(plan);
      return;
    }
    setChoosingPlan(planId);
    setMessage('');
    try {
      const result = await apiFetch('/api/billing/checkout-session', {
        method: 'POST',
        body: JSON.stringify({
          plan_id: planId,
          billing_period: publicBillingPeriodOrDefault(period),
          return_to: settingsReturnPath(),
          is_demo_mode: options.isDemoMode === true,
        }),
      });
      window.location.assign(result.url);
    } catch (error) {
      setMessage(error.message);
    } finally {
      setChoosingPlan('');
    }
  }

  async function openBillingPortal() {
    setBusyAction('portal');
    setMessage('');
    try {
      const result = await apiFetch('/api/billing/portal-session', {
        method: 'POST',
        body: JSON.stringify({ return_to: settingsReturnPath() }),
      });
      window.location.assign(result.url);
    } catch (error) {
      setMessage(error.message);
      setBusyAction('');
    }
  }

  async function refund() {
    await run(async () => {
      await apiFetch('/api/billing/refund', {
        method: 'POST',
        body: JSON.stringify({ reason: cancelReason }),
      });
      setCancelStep('idle');
      setMessage('Refund requested and subscription canceled.');
    }, 'refund');
  }

  function startRefundFlow() {
    setMessage('');
    setCancelStep('refund');
  }

  function toggleCancelFlow() {
    setMessage('');
    setCancelStep(cancelStep === 'idle' ? 'cancel' : 'idle');
  }

  async function acceptSaveOffer() {
    await run(async () => {
      await apiFetch('/api/billing/cancel', {
        method: 'POST',
        body: JSON.stringify({ accept_offer: true, reason: cancelReason }),
      });
      setCancelStep('idle');
      setMessage('Save offer applied.');
    }, 'save-offer');
  }

  async function cancelAnyway() {
    await run(async () => {
      await apiFetch('/api/billing/cancel', {
        method: 'POST',
        body: JSON.stringify({ reason: cancelReason }),
      });
      setCancelStep('idle');
      setMessage('Subscription will cancel at period end.');
    }, 'cancel');
  }

  return (
    <div className="card settings-card billing-settings">
      <div className="card-header billing-settings-header">
        <div>
          <div className="card-title">Billing</div>
          <div className="card-sub">Manage plan, payment status, refunds, and cancellation.</div>
        </div>
        <Button size="sm" onClick={() => summary.reload()}><Icon name="refresh" size={12} />Refresh</Button>
      </div>
      <div className="billing-settings-body">
        {summary.loading && !summary.data ? (
          <div className="code inline-loading"><LoadingSpinner size="sm" label="Loading billing" />Loading billing...</div>
        ) : (
          <div className="billing-summary-grid">
            <div><span className="field-label">Status</span><strong>{billing?.subscription_status || 'unpaid'}</strong></div>
            <div><span className="field-label">Plan</span><strong>{billing?.current_plan || 'No plan'}</strong></div>
            <div><span className="field-label">Period</span><strong>{billing?.billing_period || '-'}</strong></div>
            {billing?.refund_eligible_until && (
              <div><span className="field-label">Refund until</span><strong>{formatDateTime(billing.refund_eligible_until)}</strong></div>
            )}
          </div>
        )}
        <div className="billing-limits-section">
          <div>
            <div className="billing-limits-title">Plan limits</div>
            <div className="billing-limits-copy">Current usage caps and workflow frequency for this workspace.</div>
          </div>
          <div className="billing-limit-grid">
            <PlanLimitMeter label="MCP servers" state={getPlanLimitState(auth, 'mcpServers', 0)} />
            <PlanLimitMeter label="Tool monitors" state={getPlanLimitState(auth, 'toolMonitors', 0)} />
            <PlanLimitMeter label="Scheduled workflows" state={getPlanLimitState(auth, 'scheduledWorkflows', 0)} />
            <div className="plan-limit-meter">
              <span>Workflow frequency</span>
              <strong>{workflowMinIntervalSeconds(auth)}s minimum</strong>
            </div>
          </div>
        </div>
        {message && <div className="auth-message">{message}</div>}
        {canManageExistingSubscription && (
          <div className="billing-actions">
            <Button variant="primary" loading={busyAction === 'portal'} loadingLabel="Opening..." onClick={openBillingPortal}>
              <Icon name="creditCard" size={13} />Add payment method
            </Button>
          </div>
        )}
        <div className="billing-plan-picker">
          <div className="billing-plan-picker-head">
            <div>
              <div className="card-title">Choose a plan</div>
              <div className="card-sub">Subscribe or change plans without returning to onboarding.</div>
            </div>
          </div>
          <PlanPicker
            period={period}
            setPeriod={setPeriod}
            loading={plans.loading}
            plans={plans.plans}
            onChoose={choosePlan}
            choosingPlan={choosingPlan}
            currentPlanId={currentPlanId}
            currentBillingPeriod={currentBillingPeriod}
          />
          {plans.error && <div className="auth-message">{plans.error.message}</div>}
        </div>
        <div className="billing-actions">
          {canManageExistingSubscription && billing?.refund_available && (
            <Button variant="danger" loading={busyAction === 'refund'} loadingLabel="Refunding..." onClick={startRefundFlow}>
              Get a refund
            </Button>
          )}
          {canManageExistingSubscription && (
            <Button onClick={toggleCancelFlow}>
              Cancel subscription
            </Button>
          )}
        </div>
        {cancelStep !== 'idle' && (
          <div className={`cancel-flow ${isRefundFlow ? 'refund-flow' : 'cancel-flow-standard'}`}>
            <div className="cancel-flow-header">
              <span className="cancel-flow-icon">
                <Icon name={isRefundFlow ? 'creditCard' : 'alert'} size={16} />
              </span>
              <div>
                <div className="cancel-flow-title-row">
                  <h3>{flowTitle}</h3>
                  <span className={`badge ${flowBadgeClass}`}><span className="dot"></span>{flowBadgeLabel}</span>
                </div>
                <p>{flowDescription}</p>
              </div>
            </div>
            <div className="cancel-flow-meta">
              <div><span className="field-label">Status</span><strong>{billing?.subscription_status || 'unpaid'}</strong></div>
              <div><span className="field-label">{flowMetricLabel}</span><strong>{flowMetricValue}</strong></div>
            </div>
            <label className="field cancel-flow-reason">
              <span className="field-label">What changed?</span>
              <textarea
                className="textarea cancel-flow-textarea"
                rows={4}
                placeholder="Tell us what made Armature a bad fit."
                value={cancelReason}
                onChange={(e) => setCancelReason(e.target.value)}
              />
              <span className="field-help">This is optional, but it helps us understand where the product missed.</span>
            </label>
            <div className="cancel-flow-actions">
              <div className="cancel-flow-save-offer">
                <Button variant="primary" loading={busyAction === 'save-offer'} loadingLabel="Applying..." onClick={acceptSaveOffer}>
                  <Icon name="check" size={13} />Take 50% off
                </Button>
                <span>Applies to the next month and keeps monitoring active.</span>
              </div>
              <div className="cancel-flow-secondary-actions">
                <Button variant="primary" disabled={Boolean(busyAction)} onClick={() => setCancelStep('idle')}>Keep subscription</Button>
                <Button
                  className="cancel-flow-danger-action"
                  variant="ghost"
                  loading={busyAction === (isRefundFlow ? 'refund' : 'cancel')}
                  loadingLabel={isRefundFlow ? 'Refunding...' : 'Canceling...'}
                  onClick={isRefundFlow ? refund : cancelAnyway}>
                  {finalActionLabel}
                </Button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function PricingPage({ navigate, queryString = '' }) {
  const params = new URLSearchParams(queryString || '');
  const requestedPeriod = params.get('billing');
  const [period, setPeriod] = useStateBilling(isPublicBillingPeriod(requestedPeriod) ? requestedPeriod : 'monthly');
  const initialDemoMode = params.get('demo') === '1';
  const { loading, plans, error } = usePlans(period);

  function choose(planId, plan = null, options = {}) {
    if (plan?.contactSales) {
      window.openCustomPlanCta(plan);
      return;
    }
    const signupParams = new URLSearchParams({
      plan: planId,
      billing: publicBillingPeriodOrDefault(period),
    });
    if (options.isDemoMode === true) {
      signupParams.set('demo', '1');
    }
    navigate(`/signup?${signupParams.toString()}`);
  }

  return (
    <div className="pricing-page">
      <div className="pricing-page-brand">
        <img src="/frontend/assets/armature-wordmark-dark.svg" alt="Armature" />
      </div>
      <div className="pricing-head">
        <span className="pricing-eyebrow">Pricing</span>
        <h1 className="pricing-title">Simple pricing. 14-day free trial.</h1>
        <p className="pricing-lede">Try free for 14 days. Credit card required. Cancel anytime.</p>
      </div>
      {error && <div className="auth-message">{error.message}</div>}
      <PlanPicker
        period={period}
        setPeriod={setPeriod}
        loading={loading}
        plans={plans}
        onChoose={choose}
        choosingPlan=""
        initialDemoMode={initialDemoMode}
      />
    </div>
  );
}

window.SettingsBillingPage = SettingsBillingPage;
window.PricingPage = PricingPage;
