"use client";
import { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown } from 'lucide-react';
import { jsxs, jsx } from 'react/jsx-runtime';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
function TradingPanel({ symbol, currentPrice }) {
  const [orderType, setOrderType] = useState("buy");
  const [quantity, setQuantity] = useState("");
  const [portfolio, setPortfolio] = useState(null);
  const [message, setMessage] = useState(null);
  useEffect(() => {
    loadPortfolio();
  }, []);
  const loadPortfolio = /* @__PURE__ */ __name(() => {
    const storedPortfolio = localStorage.getItem("begm_portfolio");
    if (storedPortfolio) {
      setPortfolio(JSON.parse(storedPortfolio));
    } else {
      const initialPortfolio = {
        cash: 1e5,
        holdings: []
      };
      localStorage.setItem("begm_portfolio", JSON.stringify(initialPortfolio));
      setPortfolio(initialPortfolio);
    }
  }, "loadPortfolio");
  const executeTrade = /* @__PURE__ */ __name(() => {
    if (!quantity || parseFloat(quantity) <= 0) {
      setMessage({ type: "error", text: "Please enter a valid quantity" });
      return;
    }
    const qty = parseFloat(quantity);
    const total = qty * currentPrice;
    if (orderType === "buy") {
      if (total > portfolio.cash) {
        setMessage({ type: "error", text: "Insufficient funds" });
        return;
      }
      const existingHolding = portfolio.holdings.find((h) => h.symbol === symbol);
      if (existingHolding) {
        const newQuantity = existingHolding.quantity + qty;
        const newAveragePrice = (existingHolding.averagePrice * existingHolding.quantity + currentPrice * qty) / newQuantity;
        existingHolding.quantity = newQuantity;
        existingHolding.averagePrice = newAveragePrice;
        existingHolding.currentPrice = currentPrice;
      } else {
        portfolio.holdings.push({
          symbol,
          quantity: qty,
          averagePrice: currentPrice,
          currentPrice
        });
      }
      portfolio.cash -= total;
    } else {
      const existingHolding = portfolio.holdings.find((h) => h.symbol === symbol);
      if (!existingHolding || existingHolding.quantity < qty) {
        setMessage({ type: "error", text: "Insufficient shares" });
        return;
      }
      existingHolding.quantity -= qty;
      existingHolding.currentPrice = currentPrice;
      if (existingHolding.quantity === 0) {
        portfolio.holdings = portfolio.holdings.filter((h) => h.symbol !== symbol);
      }
      portfolio.cash += total;
    }
    localStorage.setItem("begm_portfolio", JSON.stringify(portfolio));
    setPortfolio({ ...portfolio });
    const orders = JSON.parse(localStorage.getItem("begm_orders") || "[]");
    orders.push({
      id: `ORD-${Date.now()}`,
      symbol,
      type: orderType,
      quantity: qty,
      price: currentPrice,
      total,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      status: "completed"
    });
    localStorage.setItem("begm_orders", JSON.stringify(orders));
    setMessage({
      type: "success",
      text: `Successfully ${orderType === "buy" ? "bought" : "sold"} ${qty} shares of ${symbol}`
    });
    setQuantity("");
    setTimeout(() => setMessage(null), 3e3);
  }, "executeTrade");
  const getHoldingInfo = /* @__PURE__ */ __name(() => {
    if (!portfolio) return null;
    const holding2 = portfolio.holdings.find((h) => h.symbol === symbol);
    return holding2;
  }, "getHoldingInfo");
  const holding = getHoldingInfo();
  return /* @__PURE__ */ jsxs("div", { className: "bg-white/5 border border-white/10 rounded-lg p-6 backdrop-blur-xl", children: [
    /* @__PURE__ */ jsxs("h3", { className: "text-lg font-bold text-white mb-4", children: [
      "Trade ",
      symbol
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex gap-2 mb-4", children: [
      /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => setOrderType("buy"),
          className: `flex-1 py-2 rounded-lg font-medium transition-all ${orderType === "buy" ? "bg-success text-white" : "bg-white/5 text-white/60 hover:bg-white/10"}`,
          children: [
            /* @__PURE__ */ jsx(TrendingUp, { size: 16, className: "inline mr-2" }),
            "Buy"
          ]
        }
      ),
      /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => setOrderType("sell"),
          className: `flex-1 py-2 rounded-lg font-medium transition-all ${orderType === "sell" ? "bg-danger text-white" : "bg-white/5 text-white/60 hover:bg-white/10"}`,
          children: [
            /* @__PURE__ */ jsx(TrendingDown, { size: 16, className: "inline mr-2" }),
            "Sell"
          ]
        }
      )
    ] }),
    holding && /* @__PURE__ */ jsxs("div", { className: "mb-4 p-3 bg-white/5 rounded-lg", children: [
      /* @__PURE__ */ jsx("p", { className: "text-xs text-white/60 mb-1", children: "Your Holdings" }),
      /* @__PURE__ */ jsxs("p", { className: "text-sm text-white", children: [
        holding.quantity,
        " shares @ $",
        holding.averagePrice.toFixed(2),
        " avg"
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "mb-4 p-3 bg-white/5 rounded-lg", children: [
      /* @__PURE__ */ jsx("p", { className: "text-xs text-white/60 mb-1", children: "Current Price" }),
      /* @__PURE__ */ jsxs("p", { className: "text-lg font-bold text-white", children: [
        "$",
        currentPrice.toFixed(2)
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "mb-4", children: [
      /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-white/80 mb-2", children: "Quantity (Shares)" }),
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "number",
          value: quantity,
          onChange: (e) => setQuantity(e.target.value),
          min: "1",
          step: "1",
          placeholder: "Enter quantity",
          className: "w-full px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-success"
        }
      )
    ] }),
    quantity && parseFloat(quantity) > 0 && /* @__PURE__ */ jsx("div", { className: "mb-4 p-3 bg-white/5 rounded-lg", children: /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-center", children: [
      /* @__PURE__ */ jsx("span", { className: "text-sm text-white/60", children: "Estimated Total" }),
      /* @__PURE__ */ jsxs("span", { className: "text-lg font-bold text-white", children: [
        "$",
        (parseFloat(quantity) * currentPrice).toFixed(2)
      ] })
    ] }) }),
    /* @__PURE__ */ jsx("div", { className: "mb-4 p-3 bg-white/5 rounded-lg", children: /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-center", children: [
      /* @__PURE__ */ jsx("span", { className: "text-sm text-white/60", children: "Available Cash" }),
      /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium text-white", children: [
        "$",
        portfolio?.cash.toLocaleString() || "0"
      ] })
    ] }) }),
    message && /* @__PURE__ */ jsx("div", { className: `mb-4 p-3 rounded-lg ${message.type === "success" ? "bg-success/20 text-success" : "bg-danger/20 text-danger"}`, children: /* @__PURE__ */ jsx("p", { className: "text-sm", children: message.text }) }),
    /* @__PURE__ */ jsxs(
      "button",
      {
        onClick: executeTrade,
        className: `w-full py-3 rounded-lg font-medium transition-all ${orderType === "buy" ? "bg-success hover:bg-success/90 text-white" : "bg-danger hover:bg-danger/90 text-white"}`,
        children: [
          orderType === "buy" ? "Buy" : "Sell",
          " ",
          symbol
        ]
      }
    ),
    /* @__PURE__ */ jsx("p", { className: "text-xs text-white/40 text-center mt-4", children: "This is a demo account. No real money is at risk." })
  ] });
}
__name(TradingPanel, "TradingPanel");

export { TradingPanel };
